java读写excel文件
需求:利用Java读写excel文件
利用jexcelapi实现Java读写excel文件的功能
首先下载并安装jexcelapi
JExcelApi v2.6.12 (1911kbytes)
解压后把jxl.jar文件添加到Java Build Path中
准备测试excel文件(D:\test\职员.xls)
Java读取excel文件
package com.test.IF.service; import java.io.File; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class HandleExcelFile { private String excelFilePath = "D:\\test\\职员.xls"; private String[][] nReadArray; private int nRows, nColumns = 0; Workbook xWorkbook; // 把Excel中的内容转换成二维数组后返回 public String[][] readExcel() { try { xWorkbook = Workbook.getWorkbook(new File(excelFilePath)); Sheet sheet = xWorkbook.getSheet(0); nRows = sheet.getRows(); nColumns = sheet.getColumns(); nReadArray = new String[nRows][nColumns]; for (int i = 1; i < nRows; i++) { for (int j = 0; j < nColumns; j++) { Cell cell = sheet.getCell(j, i); // (列, 行) String content = cell.getContents(); nReadArray[i][j] = content; } } } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } xWorkbook.close(); return nReadArray; } public static void main(String[] args) { HandleExcelFile he = new HandleExcelFile(); String[][] xLine = he.readExcel(); for (int i = 1; i < xLine.length; i++) { for (int j = 0; j < xLine[i].length; j++) { System.out.print(xLine[i][j] + "|"); } System.out.println(); } } }
测试读取程序,结果为
Java写入excel文件
package com.test.IF.service; import java.io.File; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class HandleExcelFile {// 生成Excel public void writeExcel() { try { // 生成可写入的Workbook WritableWorkbook xWritableWorkbook = Workbook.createWorkbook(new File("D:\\test\\导出测试.xls")); // 生成Worksheet WritableSheet xSheet = WritableWorkbook.createSheet("测试sheet", 0); // 往Cell设置数据 Label label00 = new Label(0, 0, "A"); // 0 列 0行 Label label01 = new Label(0, 1, "B"); // 0 列 1行 Label label02 = new Label(0, 2, "C"); // 0 列 2行 Label label10 = new Label(1, 0, "D"); // 1 列 0行 Label label11 = new Label(1, 1, "E"); // 1 列 1行 Label label12 = new Label(1, 2, "F"); // 1 列 2行 xSheet.addCell(label00); xSheet.addCell(label01); xSheet.addCell(label02); xSheet.addCell(label10); xSheet.addCell(label11); xSheet.addCell(label12); // 写入到Workbook xWritableWorkbook.write(); // 关闭Workbook xWritableWorkbook.close(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } public static void main(String[] args) { HandleExcelFile hef = new HandleExcelFile(); hef.writeExcel(); } }
测试读取程序,结果为