/**
* 下载文件,通过html页面直接将表导出
*
* @param response
* @param request
* @param fileName
* @param html
* @throws Exception
*/
@RequestMapping(params = "downloadFile")
public void downloadFile(HttpServletResponse response, HttpServletRequest request,String fileName,String html,String moneyCol,int headEndRow)
throws Exception {
final String userAgent = request.getHeader("USER-AGENT");
if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
fileName = URLEncoder.encode(fileName,"UTF-8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
fileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
}
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;" + "filename=\"" + fileName + "\"");
ServletOutputStream outputStream = response.getOutputStream();
String cnt = "\n";
List<Integer> c =new ArrayList<>();
if(StringUtils.isNotBlank(moneyCol)){
String[] split = moneyCol.split(",");
for (String s : split) {
c.add(Integer.parseInt(s));
}
}
html = removeBlank(html);
html = html.replaceAll(" ", " ");
html = html.replaceAll("<[\\s]*?br[^>]*?>|<[\\s]*?\\/[\\s]*?br[\\s]*?>", cnt);
HSSFWorkbook hssfWorkbook = ConvertHtml2Excel.table2Excel(html,c,headEndRow);
hssfWorkbook.write(outputStream);
}
工具类代码如下:
package cn.piesat.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFCellUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/****
* html转excel
* @author user
*
*/
public class ConvertHtml2Excel {
/**
* html表格转excel
*
* @param tableHtml 如
* <table>
* ..
* </table>
* @return
*/
public static HSSFWorkbook table2Excel(String tableHtml, List<Integer> moneyCols,int headEndRow) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
List<CrossRangeCellMeta> crossRowEleMetaLs = new ArrayList<CrossRangeCellMeta>();
int rowIndex = 0;
try {
Document data = DocumentHelper.parseText(tableHtml);
HSSFCellStyle contentStyle = getContentStyle(wb);
// // 生成信息列
// Element info = data.getRootElement().element("info");
// if (info != null) {
// List<Element> trLsb = info.elements("tr");
// for (Element trEle : trLsb) {
// HSSFRow row = sheet.createRow(rowIndex);
// List<Element> thLs = trEle.elements("th");
// int