方法一,利用第三方jar包:jxl.jar
public void createExcel(){try{//開啟檔案WritableWorkbook workbook = Workbook.createWorkbook(new File("test.xls"));//產生名為“第一頁”的工作表,參數0表示這是第一頁 WritableSheet sheet = workbook.createSheet("第一頁", 0);//在Label對象的構造子中指名儲存格位置是第一列第一行(0,0) //以及儲存格內容為test Label label = new Label(0,0,"test");//將定義好的儲存格添加到工作表中 sheet.addCell(label);/*產生一個儲存數位儲存格 * 必須使用Number的完整包路徑,否則有文法歧義 * 儲存格位置是第二列,第一行,值為789.123*/ jxl.write.Number number = new jxl.write.Number(1,0,756);sheet.addCell(number);sheet.insertColumn(1);workbook.copySheet(0, "第二頁", 1);WritableSheet sheet2 = workbook.getSheet(1);Range range = sheet2.mergeCells(0, 0, 0, 8);sheet2.unmergeCells(range);sheet2.addImage(new WritableImage(5, 5, 10, 20, new File("F:\\09.png")));CellView cv = new CellView();WritableCellFormat cf = new WritableCellFormat();cf.setBackground(Colour.BLUE);cv.setFormat(cf);cv.setSize(6000);cv.setDimension(10);sheet2.setColumnView(2, cv);workbook.write();workbook.close();}catch(Exception e){}}
同時,讀取Excel中的內容為:
public void displayExcel(){try {Workbook wb = Workbook.getWorkbook(new File("test.xls"));Sheet s = wb.getSheet(0);System.out.println(s.getCell(0, 0).getContents());} catch (BiffException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
方法二,利用jar包:poi-3.2-FINAL-20081019.jar
public void exportExcel(){HSSFWorkbook wb = new HSSFWorkbook();//建立工作薄HSSFFont font = wb.createFont();font.setFontHeightInPoints((short)24);font.setFontName("宋體");font.setColor(HSSFColor.BLACK.index);font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);HSSFCellStyle style = wb.createCellStyle();style.setAlignment(HSSFCellStyle.ALIGN_CENTER);style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);style.setBorderBottom(HSSFCellStyle.BORDER_THICK);style.setFont(font);HSSFSheet sheet = wb.createSheet("test");//建立工作表,名稱為testint iRow = 0;//行號int iMaxCol = 17;//最大列數HSSFRow row = sheet.createRow(iRow);HSSFCell cell = row.createCell((short)0);cell.setCellValue(new HSSFRichTextString("測試excel"));cell.setCellStyle(style);sheet.addMergedRegion(new Region(iRow,(short)0,iRow,(short)(iMaxCol-1)));ByteArrayOutputStream os = new ByteArrayOutputStream();try{wb.write(os);}catch(IOException e){e.printStackTrace();//return null;}byte[] xls = os.toByteArray();File file = new File("test01.xls");OutputStream out = null;try { out = new FileOutputStream(file); try {out.write(xls);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}
這裡補上相關的jar包:jxl.jar, poi.jar 的:
http://download.csdn.net/download/kuangfengbuyi/4658127