java创建excel的两种方式
来源:互联网 发布:软件合同范本 编辑:程序博客网 时间:2024/05/14 08:43
方法一,利用第三方jar包:jxl.jar
- public void createExcel(){
- try{
-
- WritableWorkbook workbook = Workbook.createWorkbook(new File("test.xls"));
-
- WritableSheet sheet = workbook.createSheet("第一页", 0);
-
-
- Label label = new Label(0,0,"test");
-
- sheet.addCell(label);
-
-
-
- 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) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- 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");
-
- 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();
-
- }
-
- 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) {
-
- e.printStackTrace();
- }
- } catch (FileNotFoundException e1) {
-
- e1.printStackTrace();
- }
-
-
- }
这里补上相关的jar包:jxl.jar, poi.jar 的下载地址:
http://download.csdn.net/download/kuangfengbuyi/4658127
0 0