Java操作excel

JAVA操作excel表格:
表格内容的复制(从一个文件复制某表格到另一个文件中):

步骤一:获得两个文件对象,其中book2是打开book1的缓冲

1
2
3
4
book = Workbook.getWorkbook(file);
book1 = Workbook.getWorkbook(new File(FileUtils.getExternalStoragePath(), name + "_changed.xls"));
book2 = Workbook.createWorkbook(new File(FileUtils.getExternalStoragePath(), name + "_changed.xls"), book1);

步骤二:获取表格对象

1
2
3
4
//获取原文件中的某表格对象
Sheet sheet = book.getSheet(0);
//获取写入文件中的某表格对象
WritableSheet sheet2 = book2.getSheet(sheetLocation);

步骤三:获取表格中的内容,并把内容写进表2中(icolumn是某列,row是某行)

1
2
3
4
5
6
7
8
9
10
Cell cell = sheet.getCell(column, row);
//1、把字符串写入表中
String result = cell.getContents();
sheet2.addCell(new Label(column, row, result));
//2、把Number写入表中:
String result = cell.getContents();
sheet2.addCell(new Number(column, row, Double.parseDouble(result)));
//2、把日期格式的内容写入表中:
DateCell dc = (DateCell) cell;
sheet2.addCell(new DateTime(dc).copyTo(column,row));

步骤四:最后关闭表格

1
2
3
4
5
6
7
8
9
10
11
if (book2 != null) {
book2.write();
book2.close();
}
if (book1 != null) {
book1.close();
}

if (book != null) {
book.close();
}

附:给表格加边框

1
2
3
4
5
6
7
8
//给表格加边框的format
Label label = new Label(0, 0, "");
CellFormat s = label.getCellFormat();
wcf = new WritableCellFormat(s);
wcf.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);

//使用时:
sheet2.addCell(new Label(column, row, result,wcf));