利用ApachePOI输出Excel文件

来源:互联网 发布:王者荣耀 女娲 知乎 编辑:程序博客网 时间:2024/05/22 01:40

代码中使用getSheetAt,getRow,getCell,是因为代码是复制模板excel文件然后将数据写入文件中,所以单元格都是已经存在的,如果是创建文件的话,这些地方均使用对应的create方法即可。

具体方法可查看官方doc,介绍的非常清楚

官方文档网址:http://poi.apache.org/spreadsheet/quick-guide.html

<pre name="code" class="java" style="font-family: 宋体; font-size: 21.3333px; background-color: rgb(255, 255, 255);"><pre name="code" class="java">def briefing = Briefing.findById(Long.parseLong(docId)) String realPath = ServletContextHolder.getServletContext().getRealPath('/') File fileSource = new File(realPath + '/download/template/template.xlsx') File dir = new File(realPath + '/download/' + briefing.year)        try {            if (!dir.exists())                dir.mkdir()            def monitor = MonitorEntity.findById(1)    //id=1 means sy            File fileTarget = new File(dir.getPath() + "\\" + monitor.name + "_" + briefing.year + "年第" + briefing.week + "期.xlsx")            if (!fileTarget.exists()) {                int sheetNum = 0    //第*表                def entityId = monitor.id.toString()                nioTransferCopy(fileSource, fileTarget)//文件复制                InputStream inp = new FileInputStream(fileTarget);                XSSFWorkbook xwb = new XSSFWorkbook(OPCPackage.open(inp))                xwb.setActiveSheet(0);                               XSSFSheet sheet = xwb.getSheetAt(sheetNum++);                def resultMap = source4EntityWeekly(entityId, docId)                int rowIndex_1 = ROW_LINE                resultMap.each {                    key, value ->                        XSSFRow row = sheet.getRow(rowIndex_1);                        XSSFCell cellSource = row.getCell(0)                        cellSource.setCellValue(String.valueOf(key))                        XSSFCell cellCount = row.getCell(1)                        cellCount.setCellValue(value)                        rowIndex_1++                }                                }                xwb.setActiveSheet(0)                OutputStream out = new FileOutputStream(fileTarget);                xwb.write(out);                inp.close();                out.close();            }            return fileTarget        }


                                             
0 0
原创粉丝点击