java导出excel问题记录
生活随笔
收集整理的這篇文章主要介紹了
java导出excel问题记录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
最近做了一個導出excel的功能,在網上一頓找,終于完成了,寫個文章做個總結,希望有人能用上。
一、創建單元格,給單元格賦值
示例:
引包 <!-- excel poi --><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.0</version></dependency> // 注意點:模板必須在template下,templates這樣的文件夾是不好用的 InputStream inputStream = this.getClass().getResourceAsStream("/template/excel/invoice.xlsx"); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); Cell cell = sheet.getRow(1).getCell(2); cell.setCellValue(1);單元格x、y下標都是從0開始的
2.單元格樣式
示例:
CellStyle cellStyle = workbook.createCellStyle(); //合并單元格,四個參數分別是起始行,終止行,起始列,終止列 //也就是把第二行的第二個和第三個單元格合并 CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2); sheet.addMergedRegion(region); //設置行高 sheet.getRow(1).setHeightInPoints(51.75f); //設置單元格邊框 cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //字體水平居中和垂直居中 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //自動換行 cellStyle.setWrapText(true); cell.setCellStyle(cellStyle);在合并單元格和設置邊框時遇到了點問題
1、合并單元格后設置字體居中需要把excel模板里的合并單元格格式去掉,要不有沖突,字體無法居中
2、在合并單元格上設置邊框只能設置起始單元格,我的做法是比如1.2單元格合并了,在設置邊框時先將1單元格值賦進去,再將2單元格賦值"",感覺這樣做很傻,網上應該有更好的辦法,但是我沒有去嘗試,如果有需要可以自己去查。
3.將圖片插入excel中
示例:
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); BufferedImage bufferImg = ImageIO.read(new File("C:\\Users\\jianl\\Desktop\\test.png"); ImageIO.write(bufferImg, "png", byteArrayOut); Drawing patriarch = sheet.createDrawingPatriarch(); ClientAnchor anchor = new XSSFClientAnchor(10000, 20000, -360000, 0,(short)0 , 0, (short) 3, 1); // 插入圖片 patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));這塊主要要注意的就是XSSFClientAnchor里面的8個參數
前四個是偏移量,就是相對于你圖片要放的位置的偏移,1.3是左右偏移,2.4是上下偏移
后四個是要放的位置,5.7是圖片寬的位置,數值就是單元格位置,6.8是圖片長,也是所在單元格位置
總結
我導出excel就用到了這些,希望能對你有幫助
總結
以上是生活随笔為你收集整理的java导出excel问题记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转) Csrss进程剖析
- 下一篇: 斐讯路由刷机