使用jexcelapi接口对excel进行读取和写入(jexcelapi只能操作xls后缀的文件)
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
写入文件:
* 向Excel文件中写入内容
* 内容为一个ArrayList格式
*/
public static void WriteToExcel() throws IOException, WriteException {
String str = "[{\"person\":{\"name\":\"xiaoming\"}},{\"person\":{\"name\":\"xiaohong\"}},{\"person\":{\"name\":\"xiaohuang\"}},{\"person\":{\"name\":\"xiaolan\"}},{\"person\":{\"name\":\"xiaohei\"}}]";
JSONArray array = JSONArray.fromObject(str);
File xlsFile = new File("./src/test/resources/testFile.xls");//这里定义一个文件xls文件名,不存在时新建一个文件
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);//创建一个工作薄
WritableSheet sheet = workbook.createSheet("sheet1", 0);//创建的sheet名字为sheet1,创建多个时,增加index数
for (int row = 0; row < array.size(); row++) {
for (int col = 0; col < 1; col++) {
sheet.addCell(new Label(col, row, array.getJSONObject(row).getJSONObject("person").getString("name")));//向cell中输入内容
}
}
workbook.write();
workbook.close();
System.out.println("更新Excel完成");
}
读取文件:
* 读取Excel的文件
*/
public static void readExcel() throws IOException, BiffException {
File xlsFile = new File("./src/test/resources/testFile.xls");
Workbook workbook = Workbook.getWorkbook(xlsFile);//获得工作簿对象
Sheet[] sheets = workbook.getSheets();//获得所有工作表
//遍历工作表
if (sheets != null) {
for (Sheet sheet : sheets) {
int rows = sheet.getRows();//获得行数
int cols = sheet.getColumns();//获得列数
//读取数据
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.printf("%10s", sheet.getCell(col, row).getContents());
}
System.out.println();
}
}
workbook.close();
}
}