//主要方法 list是要写入的数据
private void writeExcel(HttpServletResponse response, List list) {
if(list==null||list.size()==0) {
return;
}
//Excel文件path(这里是从静态常量获取的) “文件路径”
String remoteFilePath=GlobalConstant.ZGSQ_FILE_PATH;
String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
FTPClient ftpClient=null;
String path = null;
try {
ftpClient = ftpClientPool.borrowObject();
ftpClient.changeWorkingDirectory("/");
path = new String(remoteFilePath.getBytes(“UTF-8”), “ISO-8859-1”);
} catch (NoSuchElementException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//写入数据,并下载*****************************************************
InputStream is = null;
BufferedOutputStream fos=null;
XSSFWorkbook xSSFWorkbook=null;
XSSFSheet xSSFSheet=null;
try {
response.reset();
String newName = URLEncoder.encode("固定资产增置单"+System.currentTimeMillis()+".xlsx", "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=\""+ newName + "\"");
is = ftpClient.retrieveFileStream(path);
xSSFWorkbook = new XSSFWorkbook(is);
//获取第一个sheet
xSSFSheet = xSSFWorkbook.getSheetAt(0);
} catch (Exception e1) {
e1.printStackTrace();
}
if(xSSFSheet != null){
try {
fos =new BufferedOutputStream(response.getOutputStream());
//构建每行的数据内容
int rowNum = 1;
for (AssetConversionDownloadExcel data : list) {
if (data == null) {
continue;
}
//输出行数据
Row row = xSSFSheet.createRow(rowNum++);
int cellNum = 0;
Cell cell;
// 序号
cell = row.createCell(cellNum++);
// 项目编号
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getProjectNo() ? "" : data.getProjectNo());
// 项目名称
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getProjectNm() ? "" : data.getProjectNm());
// 所在金额
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getProjectAmount() ? null : data.getProjectAmount());
}
xSSFWorkbook.write(fos);
fos.flush();
ftpClient.completePendingCommand();
ftpClientPool.returnObject(ftpClient);
}
catch(Exception e) {
e.printStackTrace();
}finally {
try {
if (null != is) {
is.close();
}
if (null != fos) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}