首页 > 代码库 > Java 导入Excel (直接插入)
Java 导入Excel (直接插入)
@ResponseBody
@RequestMapping(valuehttp://www.mamicode.com/= "http://www.mamicode.com/excel")
public String commonFileExcel(@RequestParam String name, @RequestParam String table, HttpServletRequest request) {
String path = RunTimeConfig.getRealPath(PhotoType.getPath(PhotoType.EXCEL)) + "/" + name;
try {
Workbook wb = null;
try {
wb = new HSSFWorkbook(new FileInputStream(new File(path)));// 2003excel
} catch (Exception e) {
wb = new XSSFWorkbook(new FileInputStream(new File(path)));// 2007excel
}
Sheet sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
int cellNum;
Row row;
Cell cell;
String columns = "";
for (int i = 1; i <= rowNum; i++) {
String valuehttp://www.mamicode.com/= "";
row = sheet.getRow(i);
cellNum = row.getLastCellNum();// 列
for (int j = 0; j < cellNum; j++) {// 对一行的每个列进行解析
cell = row.getCell(j);
if (i == 1) {
if (columns.equals("")) {// 全部都以字符串形式取出
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
columns = table + "." + cell.getStringCellValue();// 保险起见以表名.列名
}
} else {
if (cell != null) {// 全部都以字符串形式取出
cell.setCellType(Cell.CELL_TYPE_STRING);
columns = columns + "," + table + "." + cell.getStringCellValue();// 保险起见以表名.列名
}
}
} else {
if (value.equals("")) {// 全部都以字符串形式取出
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
valuehttp://www.mamicode.com/= "‘" + cell.getStringCellValue() + "‘";
}
} else {
if (cell != null) {// 全部都以字符串形式取出
cell.setCellType(Cell.CELL_TYPE_STRING);
value = http://www.mamicode.com/value +"," + "‘" + cell.getStringCellValue() + "‘";
}
}
}
}
if (i != 1) {
baseValuesServiceI.insert(table, value, columns);
System.out.println("insert into " + table + "(" + columns + ") values (" + value + ")");
}
}
} catch (FileNotFoundException e) {
System.out.println("未找到指定路径的文件!");
e.printStackTrace();
log.error(e);
return "fail";
} catch (IOException e) {
e.printStackTrace();
log.error(e);
return "fail";
}
return "success";
}
Java 导入Excel (直接插入)