㈠ 用java将数据导出到wps表格中,怎么实现
importjava.io.IOException;
importjava.io.OutputStream;
importjava.math.BigDecimal;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
publicclassTest{
(HttpServletResponseresponse,
java.util.ListqueryList,intflag,String[]ywName,StringfileName)
throwsIOException{
response.setContentType("application/vnd.ms-excel;charset=GBK");
response.addHeader("Content-Disposition","attachment;filename="
+newString(fileName.getBytes("GBK"),"ISO8859_1"));
OutputStreamoutput=response.getOutputStream();
//创建新的Excel工作簿
HSSFWorkbookworkbook=newHSSFWorkbook();
HSSFSheetsheet;
HSSFRowrow;
HSSFCellcell;
sheet=workbook.createSheet();
StringstrReportName="查询结果列表";
workbook.setSheetName(0,strReportName);//新建一名为strReportName的工作表
//创建表头
//在索引0的位置创建行(最顶端的行)
row=sheet.createRow((short)0);
for(intkk=0;kk<ywName.length;kk++){
//在索引0的位置创建单元格(左上端)
cell=row.createCell(kk);
//cell.setCellStyle(HSSFCellStyle.ALIGN_CENTER);
//定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置字符显示格式,以unicode格式显示
//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//在单元格中输入一些内容
cell.setCellValue(ywName[kk]);
}
intline=1;
intcellWidth=ywName.length;
for(inti=0;i<queryList.size();i++){
//HashMappersonInfo=(HashMap)queryList.get(i);
Object[]personInfo=(Object[])queryList.get(i);
row=sheet.createRow((short)line);
for(intj=0;j<cellWidth;j++){
cell=row.createCell(j);
//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
if(personInfo[j+flag]instanceofInteger){
if(personInfo[j+flag]!=null)
cell.setCellValue((Integer)personInfo[j+flag]);
else
cell.setCellValue("");
}elseif(personInfo[j+flag]instanceofBigDecimal){
if(personInfo[j+flag]!=null)
cell.setCellValue(newDouble(personInfo[j+flag]
.toString()));
else
cell.setCellValue("");
}elseif(personInfo[j+flag]instanceofDouble){
if(personInfo[j+flag]!=null)
cell.setCellValue((Double)personInfo[j+flag]);
else
cell.setCellValue("");
}else{
if(personInfo[j+flag]!=null)
cell.setCellValue(personInfo[j+flag].toString());
else
cell.setCellValue("");
}
}
line++;
}
workbook.write(output);
output.flush();
output.close();
}
}
给你个工具方法,把它放到类里面,直接调用就可以了
我解释下参数
/**
* @param response 获取响应,在action中使用getResponse()
* @param 数据集(从数据库获得的数据,注意和ywName顺序对应)
* @param flag 有行号为1,无行号为0
* @param ywName excel中每列名称
* @param fileName excel名
*/
//导出代码
String[] yName={"员工号","员工名称","机构号","机构名称","***xxx","dddd"};
ExportExcel.createDtcxEXCEL(getResponse(), pgr.getData(), 1,yName , "龙大哥_"+new Date().toString());
最后 导出,默认文件名是“龙大哥_(当天日期)”
这个代码放心用,只要把参数传对,就可导出EXCEL
如果觉得可行,望采纳