// JXL读取Excel文件的具体原理在上个博客中已经谈过,如有不清楚的地方,请看上篇博客内容 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; /** * 用JXL对Excel文件的读取和写入实验 * * @author Administrator * */ public class ExcelIO { /** * 对指定Excel文件进行读操作 * * @param inputFile * 指定的Excel文件 */ public static void readExcel(File inputFile) { // Excel文件对象引用 Workbook workbook = null; try { // 获取指定Excel文件对象 workbook = Workbook.getWorkbook(inputFile); // 通过Excel文件对象获取指定工作表 Sheet sheet = workbook.getSheet(0); // 对工作表数据进行读取 int i = 0; while (true) { // 单元格引用 Cell cell = null; try { // 读取指定工作表中的第0列单元格,如果越界则退出 cell = sheet.getCell(0, i); } catch (ArrayIndexOutOfBoundsException e) { break; } // 获取读取单元格内容,并打印 String str = cell.getContents(); System.out.print(str + "\t"); // 读取指定列工作表第1列单元格内容,并打印 cell = sheet.getCell(1, i); str = cell.getContents(); System.out.print(str + "\t"); // 读取指定列工作表第2列单元格内容,并打印 cell = sheet.getCell(2, i); str = cell.getContents(); System.out.print(str + "\t"); System.out.println(); // 自增循环读取,读完整个工作表 ++i; } } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 关闭Excel文件资源 if (workbook != null) { workbook.close(); workbook = null; } } catch (Exception e) { e.printStackTrace(); } } } /** * 写入指定Excel文件 * * @param outputFile * 指定写入的Excel文件 */ public static void writeExcel(File outputFile) { // 可写Excel文件引用 WritableWorkbook writableWorkbook = null; try { // 创建可写Excel文件对象 writableWorkbook = Workbook.createWorkbook(outputFile); // 创建可写Excel文件工作簿对象 WritableSheet writableSheet = writableWorkbook .createSheet("用户表", 1); // 给指定单元格写入内容,并添加到指定工作簿 writableSheet.addCell(new Label(1, 1, "Hello world")); // 写入,如果没有这句Excel打开会出现文件格式错误 writableWorkbook.write(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { // 关闭Excel文件对象 if (writableWorkbook != null) { writableWorkbook.close(); writableWorkbook = null; } } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { // 读取指定文件 readExcel(new File("D:\\temp\\test.xls")); // 写入指定文件 writeExcel(new File("D:\\temp\\test01.xls")); } }