方法一,利用第三方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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.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");//创建工作表,名称为test int 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 block e.printStackTrace(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
这里补上相关的jar包:jxl.jar, poi.jar 的下载地址:
http://download.csdn.net/download/kuangfengbuyi/4658127