62,628
社区成员
发帖
与我相关
我的任务
分享public static Workbook getWorkBook(String path) {
Workbook workbook = null;
InputStream is = null;
Sheet sheet = null;
try {
is = new FileInputStream(ExcelUtil.getFile(path));
workbook = WorkbookFactory.create(is);
// 看了有兄弟说代码创建的Exel文件因为没有sheet导致打开报错(直接新建excel默认三个sheet)然而这代码无用
if (workbook.getNumberOfSheets() == 0) {
sheet = workbook.createSheet("sheet1");
Row row = sheet.createRow(0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}public static File getFile(String path) {
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
e.getLocalizedMessage();
e.getMessage();
}
}
return file;
} public static void writeDataToLocalFile(String path,String[] fields, List<Object> data) {
System.out.println("start to writing............");
Workbook workbook = null;
FileOutputStream fos = null;
Sheet sheet = null;
try {
workbook = ExcelUtil.getWorkBook(path);
sheet = workbook.getSheetAt(0);
if (null == sheet.getRow(0)) {
Row header = sheet.createRow(0);
for (int i = 0; i < fields.length; i++) {
Cell cell = header.createCell(i);
cell.setCellValue(fields[i]);
}
}
if (null != data) {
for (int i = 0; i < data.size(); i ++){
List<String> list = MatchData.parseBeanToList(data.get(i));
System.out.println("当前已有 " + sheet.getPhysicalNumberOfRows() + " 行数据");
Row dataRow = sheet.createRow(sheet.getPhysicalNumberOfRows());
for (int j = 0; j < list.size(); j++) {
Cell cell = dataRow.createCell(j);
cell.setCellValue(list.get(j));
}
}
}
fos = new FileOutputStream(ExcelUtil.getFile(path));
workbook.write(fos);
} catch (Exception e) {
System.out.println("error....");
e.printStackTrace();
e.getLocalizedMessage();
e.getMessage();
} finally {
ExcelUtil.close(fos,workbook);
}
System.out.println("finished");
}