日期:2014-05-20 浏览次数:20731 次
package cn.com.zte.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import jxl.Sheet; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; /** * 读写excel文件 * @author huangshaojun * */ public class TestExcel { /** * 写Excel文件 * @param fileName */ public void writeExcel(String fileName) { OutputStream outStream = null; //输出流 WritableWorkbook writeWork = null; //写工作薄 try { outStream = new FileOutputStream(fileName); //文件输出流 writeWork = Workbook.createWorkbook(outStream); //新建工作薄 WritableSheet outSheet = writeWork.createSheet("old", 0); //新建工作页 int k = 1; for(int i = 0 ; i < 10; i++) { for(int j = 0 ; j < 10 ; j++) { Label lable = new Label(i , j , String.valueOf(k++)); //新建单元格 outSheet.addCell(lable); //把单元格添加到工作页中 } } outSheet.mergeCells(1, 1, 1, 5); //合并单元格,参数格式(开始列,开始行,结束列,结束行) writeWork.write(); writeWork.close(); //关闭 outStream.close(); } catch(Exception e) { e.printStackTrace(); } } /** * 读Excel文件 * @param fileName */ public void readExcel(String fileName) { InputStream inStream = null; Workbook workBook = null; try { inStream = new FileInputStream(fileName); //输入流 workBook = Workbook.getWorkbook(inStream); //工作薄 Sheet inSheet = workBook.getSheet("old"); //sheet页 int columns = inSheet.getColumns(); int rows = inSheet.getRows(); StringBuffer CellContent = new StringBuffer(); for(int i = 0; i < columns; i++) { for(int j = 0 ; j < rows ; j++) { CellContent.append(inSheet.getCell(i, j).getContents()); //读单元格内容 CellContent.append(" "); } System.out.println(CellContent); CellContent.delete(0, CellContent.length()); } } catch(Exception e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { TestExcel te = new TestExcel(); te.writeExcel("D:\\old.xls"); te.readExcel("D:\\old.xls"); } }