工作中遇到批量导入功能,需要把上传的Excel表格中的数据取出存到数据库中,总结一下:
需要使用到jxl库:
直接上代码:
public static ArrayList<Map> importToExcel(File file)
{
ArrayList<Map> arr = new ArrayList<Map>();
String[] title;
Workbook wwb = null;
try
{
wwb = Workbook.getWorkbook(file);
int sheetNumber = wwb.getNumberOfSheets();
System.out.println("sheetNumber:" + sheetNumber);
for (int m = 0; m < sheetNumber; m++)
{
Sheet ws = wwb.getSheet(m);
int rowCount = ws.getRows();
int columeCount = ws.getColumns();
System.out.println("rowCount:" + rowCount);
System.out.println("columeCount:" + columeCount);
if (rowCount > 1 && columeCount > 0)
{
title = new String[columeCount];
for (int k = 0; k < columeCount; k++)
{
title[k] = ws.getCell(k, 0).getContents().trim();
}
for (int i = 1; i < rowCount; i++)
{
Map dataMap = new HashMap();
for (int j = 0; j < columeCount; j++)
{
if (ws.getCell(j, i).getType() == CellType.DATE)
{
Date date = ((DateCell) ws.getCell(j, i)).getDate();
long offset = tz.getOffset(date.getTime());
date.setTime(date.getTime() - offset);
dataMap.put(title[j], date);
}
else
{
dataMap.put(title[j], ws.getCell(j, i).getContents());
}
}
arr.add(dataMap);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (wwb != null)
{
wwb.close();
wwb = null;
}
}
return arr;
}