工作时用到写入Excel的场景,发现有Apache POI提供的jar包与JXL的jar包。实际操作时,个人感觉poi比较高大上,基本上能够实现excel的大部分功能,包括字体设置、表格设置等内容,但相对门槛较高,操作复杂。相比POI,JXL操作简单,容易入门,相比而言得到的EXCEL文档也是比简单,不需要特殊的格式化。
public static void write2xlsStrpublic static void write2xlsStr(WritableWorkbook book, String[] title,
List lst) throws RowsExceededException, WriteException,
IOException {
WritableSheet sheet = book.createSheet("Page_First", 0);
int colSize = title.length;
int rowSize = lst.size();
for (int i = 0; i < colSize; i++)
sheet.addCell(new Label(i, 0, title[i]));
for (int i = 0; i < rowSize; i++)
for (int j = 0; j < colSize; j++)
sheet.addCell(new Label(j, i + 1, lst.get(i)[j]));
book.write();
book.close();
}
public static void write2xlsLst(WritableWorkbook book, String[] title,
List> lst)
throws RowsExceededException,
WriteException, IOException {
WritableSheet sheet = book.createSheet("Page_First", 0);
int colSize = title.length;
int rowSize = lst.size();
for (int i = 0; i < colSize; i++)
sheet.addCell(new Label(i, 0, title[i]));
for (int i = 0; i < rowSize; i++)
for (int j = 0; j < colSize; j++)
sheet.addCell(new Label(j, i + 1, lst.get(i).get(j)));
book.write();
}
public static WritableWorkbook getWorkBook(String filename)
throws IOException {
return Workbook.createWorkbook(new File(filename));
}
public static void write2xlsMap(WritableWorkbook book, String sheetname,
int index, List
throws RowsExceededException, WriteException, IOException {
WritableSheet sheet = book.createSheet(sheetname, index);
int colSize = lst.get(0).keySet().size();
int rowSize = lst.size();
if (colSize < 1)
return;
if (rowSize < 1)
return;
int ind = 0;
String[] title = new String[colSize];
for (String str : lst.get(0).keySet()) {
sheet.addCell(new Label(ind, 0, str));
title[ind++] = str;
}
int col_index = 0;
int row_index = 0;
int names = 1;
for (int i = 0; i < rowSize; i++) {
col_index = 0;
for (int j = 0; j < colSize; j++) {
sheet.addCell(new Label(col_index, row_index + 1, ""
+ lst.get(row_index).get(title[col_index])));
col_index++;
}
if (row_index++ > MAX_ITEMS) {
row_index = 0;
sheet = book.createSheet(sheetname + "add_" + (names), index
+ (names++));
}
}
book.write();
}
调用时,可参考如下方式:
WritableWorkbook book = getWorkBook("Filepath");
// your data format: list for list
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!