您的位置:首页 > 运维架构 > Apache

利用ApachePOI输出Excel文件

2015-10-20 11:41 579 查看
代码中使用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
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: