日期:2014-05-20 浏览次数:20905 次
package jxl; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class JxlExcelWriter { /** * @param out 输出excel文件. * @param br 输入txt文件. */ public void writeExcel(OutputStream out, BufferedReader br) { if(br == null) { throw new IllegalArgumentException("写excel流需要file!"); } try { WritableWorkbook workbook = Workbook.createWorkbook(out); WritableSheet ws = workbook.createSheet("sheet 1", 0); int rowNum = 0; // 写入行数 //文件行数 String line = null; while((line = br.readLine()) != null){ String[] data = line.split("\t"); Object[] cells = (Object[]) data; putRow(ws, rowNum, cells); // 写一行到sheet rowNum++; } workbook.write(); workbook.close(); // 关闭、保存Excel System.out.print("success!"); } catch (RowsExceededException e) { System.out.println("jxl write RowsExceededException: "+e.getMessage()); } catch (WriteException e) { System.out.println("jxl write WriteException: "+e.getMessage()); } catch (IOException e) { System.out.println("jxl write file i/o exception!, cause by: "+e.getMessage()); } } private void putRow(WritableSheet ws, int rowNum, Object[] cells) throws RowsExceededException, WriteException { for(int i=0; i<cells.length; i++) { Label cell = new Label(i, rowNum, ""+cells[i]); ws.addCell(cell); } } public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader("e:/input/data.txt")); OutputStream out = new FileOutputStream(new File("e:/out/test.xls")); JxlExcelWriter jxlExcelWriter = new JxlExcelWriter(); jxlExcelWriter.writeExcel(out, br); out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }