㈠ 用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
如果覺得可行,望採納