Auxiliary class code:
package com.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mode.Swpsc;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public final class ExcelExport {
OutputStream out =null;
String excelName = "Detailed Shipment Statistics";
//Access URL: http://localhost:8080/excelExport/servlet/ExcelExportServlet
public void Excelexport(HttpServletRequest request, HttpServletResponse response,List<Swpsc> list){
try {
response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("UTF-8"),"ISO8859-1")+".xls");
} catch (UnsupportedEncodingException e1) {
// TODO auto-generated catch block
e1.printStackTrace();
}
//Transcoding to prevent garbled characters
String[] headers = new String[]{"serial number", "delivery note number", "customer name", "order number", "print name", "shipping quantity", "unit price", "delivery Date","Total Amount"};
try {
out = response.getOutputStream();
out.flush();
exportExcel(excelName,headers, getList(list), out,"yyyy-MM-dd");
out.close();
System.out.println("Excel export successfully!");
} catch (FileNotFoundException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
}
/**
*
* @Description: Simulate the data queried from the database, usually several columns in the data table
* @Auther: lujinyong
* @Date: 2013-8-22 2:53:58 PM
*/
public List<Map<String,Object>> getList(List<Swpsc> lists){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for(int i = 0; i<lists.size();i++){
Map<String,Object> map = new HashMap<String, Object>();
map.put("xh",i+1);
map.put("shbh", lists.get(i).getPsb().getPsb004());
map.put("khmz", lists.get(i).getPsb().getUsc().getUsc003());
if(lists.get(i).getPsc007().equals("A")){
map.put("ddbh", lists.get(i).getDdc().getDds().getDds004());
map.put("ypmz", lists.get(i).getDdc().getDdc004());
}
if(lists.get(i).getPsc007().equals("B")){
map.put("ddbh", lists.get(i).getDda().getDdz().getDdz004());
map.put("ypmz", lists.get(i).getDda().getDda004());
}
if(lists.get(i).getPsc007().equals("C")){
map.put("ddbh", lists.get(i).getDdf().getDde().getDde004());
map.put("ypmz", lists.get(i).getDdf().getDdf004());
}
map.put("fhsl",lists.get(i).getPsc004() );
map.put("dj", lists.get(i).getDj());
map.put("jhrq", lists.get(i).getPsb().getZdDate());
map.put("zje", lists.get(i).getMoney());
list.add(map);
}
return list;
}
/**
*
* @Description: Generate excel and export to client (local)
* @Auther: lujinyong
* @Date: 2013-8-22 3:05:49 PM
*/
protected void exportExcel(String title,String[] headers,List mapList,OutputStream out,String pattern){
//declare a workbook
HSSFWorkbook workbook = new HSSFWorkbook();
// generate a form
HSSFSheet sheet = workbook.createSheet(title);
//Set the default column width of the table to 15 characters
sheet.setDefaultColumnWidth(20);
//Generate a style to set the title style
HSSFCellStyle style = workbook.createCellStyle();
//set these styles
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//generate a font
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//Apply the font to the current style
style.setFont(font);
// Generate and set another style for styling the content
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// generate another font
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// apply the font to the current style
style2.setFont(font2);
//Generate table header row
HSSFRow row = sheet.createRow(0);
for(int i = 0; i<headers.length;i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
for (int i=0;i<mapList.size();i++) {
Map<String,Object> map = (Map<String, Object>) mapList.get(i);
row = sheet.createRow(i+1);
int j = 0;
Object value = null;
value=map.get("xh");
if(value instanceof Integer){
row.createCell(j++).setCellValue(String.valueOf(value));
}
row.createCell(j++).setCellValue(map.get("shbh").toString());
row.createCell(j++).setCellValue(map.get("khmz").toString());
row.createCell(j++).setCellValue(map.get("ddbh").toString());
row.createCell(j++).setCellValue(map.get("ypmz").toString());
value=map.get("fhsl");
if(value instanceof Integer){
row.createCell(j++).setCellValue(String.valueOf(value));
}
value=map.get("dj");
if(value instanceof Double){
row.createCell(j++).setCellValue(String.valueOf(value));
}
row.createCell(j++).setCellValue(map.get("jhrq").toString());
value=map.get("zje");
if(value instanceof Double){
row.createCell(j++).setCellValue(String.valueOf(value));
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace ();
}
}
}
Calling code in Controller:
@RequestMapping(value = "/Order_FH_TJ_index")
public ModelAndView indexRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession httpsession=request.getSession();
ModelAndView mav=new ModelAndView();
//Whether the website is closed, close to the close page
if(!PubMessage.isCloseweb()&&!((Swuse) httpsession.getAttribute("useinfo")).getUse002().equals("admin")){
mav.setViewName("redirect:/close.jsp");
return mav;
}
//Check if it is logged in
if(httpsession.getAttribute("useinfo")==null){
mav.setViewName("redirect:/login.jsp");
return mav;
}
PageBean pb = new PageBean();
if(request.getParameter("othersql")!=null&&!request.getParameter("othersql").isEmpty())
pb.setOthersql(request.getParameter("othersql"));
if(request.getParameter("othersql3")!=null&&!request.getParameter("othersql3").isEmpty())
pb.setOthersql3(request.getParameter("othersql3"));
if(request.getParameter("othersql4")!=null&&!request.getParameter("othersql4").isEmpty())
pb.setOthersql4(request.getParameter("othersql4"));
if(request.getParameter("othersql8")!=null&&!request.getParameter("othersql8").isEmpty())
pb.setOthersql8(request.getParameter("othersql8"));
else pb.setOthersql8("Z");
SwpscService swpscService = (SwpscService) SpringContextUtil.getBean("SwpscService");
mav.addObject("pageobj",swpscService.serachList2(pb));
if(pb.getOthersql8().equals("P")){
ExcelExport excelExport=new ExcelExport();
excelExport.Excelexport(request, response, pb.getResultList());
return null;
}
mav.setViewName("Order_FH_tongji");
return mav;
}
Foreground jsp call button:
<button type="button" class="btn btn-success" style="margin-left:7px;" onClick="excel()">导出excel</button>
js to access the code of the method in the backend Controller:
function excel() {
var params = [['othersql',$.trim($("#rolename").val().toString())], ['othersql3',$.trim($("#startDate").val().toString())],
['othersql4',$.trim($("#endDate").val().toString())],['othersql8',"P"]];
form_submit('Order_FH_TJ_index','post',params,'_self');
}
The required jar package has been uploaded: poi-3.7-20101029.jar