文件上传下载

下载

场景:用户点击按钮,在后台生成文件,并下载到客户端

导出Excel

客户端程序

        var link = document.createElement('a');
        link.setAttribute("download", "");
        link.href = "${ctx}/reportExcel";
        link.click();
        link.remove();

表单提交

var form = this.$('#form');
form.attr('action', '${ctx}/msrIron/queryIronReport2');
form.submit(function ()
{
    return true;
})
form[0].submit();
form[0].action = '${ctx}/msrIron/queryIronReport1';

兼容Chrome和IE

服务端(方法一)

将文件留写入 ServletOutputStream对象中即可

// 生成数据, 转发到jsp

jsp:

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
<%@ include file="/WEB-INF/views/include.inc.jsp"%>

<%
    response.setContentType("application/vnd.ms-excel;charset=GBK");
    String fileName = "铁水计量明细报表";
    response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1") + ".xls");
%>
<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
<head>
    <meta http-equiv=Content-Type content="text/html; charset=gb2312">
    <xml>
        <x:ExcelWorkbook>
            <x:ExcelWorksheets>
                <x:ExcelWorksheet>
                    <x:Name>生铁计量明细报表</x:Name>
                    <x:WorksheetOptions>
                        <x:DefaultRowHeight>310</x:DefaultRowHeight>
                        <x:Print>
                            <x:ValidPrinterInfo/>
                            <x:PaperSizeIndex>9</x:PaperSizeIndex>
                            <x:HorizontalResolution>-3</x:HorizontalResolution>
                            <x:VerticalResolution>0</x:VerticalResolution>
                        </x:Print>
                        <x:Selected/>
                        <x:Panes>
                            <x:Pane>
                                <x:Number>6</x:Number>
                                <x:ActiveRow>4</x:ActiveRow>
                                <x:ActiveCol>4</x:ActiveCol>
                            </x:Pane>
                        </x:Panes>
                        <x:ProtectContents>False</x:ProtectContents>
                        <x:ProtectObjects>False</x:ProtectObjects>
                        <x:ProtectScenarios>False</x:ProtectScenarios>
                    </x:WorksheetOptions>
                </x:ExcelWorksheet>
            </x:ExcelWorksheets>
            <x:WindowHeight>660</x:WindowHeight>
            <x:WindowWidth>12000</x:WindowWidth>
            <x:WindowTopX>0</x:WindowTopX>
            <x:WindowTopY>1395</x:WindowTopY>
            <x:ProtectStructure>False</x:ProtectStructure>
            <x:ProtectWindows>False</x:ProtectWindows>
        </x:ExcelWorkbook>
    </xml>
</head>
<body>
<table x:str border=0 cellpadding=0 cellspacing=0 width=1092
       style='border-collapse:collapse;table-layout:fixed;820pt'>
    <%--<thead>--%>
    <tr>

        <th nowrap="nowrap">炉名</th>
        <th nowrap="nowrap">炉次</th>
        <th nowrap="nowrap">罐号</th>
        <th nowrap="nowrap">发货单位</th>
        <th nowrap="nowrap">收货单位</th>
        <th nowrap="nowrap">毛重t</th>
        <th nowrap="nowrap">毛重时间</th>
        <th nowrap="nowrap">皮重t</th>
        <th nowrap="nowrap">皮重时间</th>
        <th nowrap="nowrap">净重t</th>
        <th nowrap="nowrap">实重t</th>
        <th nowrap="nowrap">净重时间</th>
        <th nowrap="nowrap">生产重量t</th>

    </tr>
    </thead>
    <tbody align="center">
    <c:forEach items="${list}" var="row" varStatus="num">
        <tr height="25" <c:if test="${row.heatname=='小计:'}"> class="a1" </c:if> onclick="tagscheck(this)">

            <td nowrap="nowrap">${row.heatname}&nbsp;</td>
            <td nowrap="nowrap">${fn:substring(row.sequence_no,fn:length(row.sequence_no)-5,fn:length(row.sequence_no))}&nbsp;</td>
            <td nowrap="nowrap">${row.kettle_no}&nbsp;</td>
            <td nowrap="nowrap">${row.sourcename}&nbsp;</td>
            <td nowrap="nowrap">${row.targetname}&nbsp;</td>
            <td nowrap="nowrap" align="right">${row.gross}&nbsp;</td>
            <td nowrap="nowrap">
                <fmt:formatDate value="${row.grosstime}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </td>
            <td nowrap="nowrap" align="right">
                <c:if test="${row.tare>60}">
                    <c:if test="${row.heatname!='小计:'}">
                        <strong><font  color="red">${row.tare}</font></strong>
                    </c:if>
                </c:if>
                <c:if test="${row.tare>60}">
                    <c:if test="${row.heatname=='小计:'}">${row.tare}</c:if>
                </c:if>
                <c:if test="${row.tare<=60}"> ${row.tare} </c:if>&nbsp;
            </td>
            <td nowrap="nowrap">
                <fmt:formatDate value="${row.taretime}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </td>
            <td nowrap="nowrap" align="right">
                <c:if test="${row.heatname=='小计:'}">
                    <strong><font  color="red">${row.suttle}</font></strong>
                </c:if>
                <c:if test="${row.heatname!='小计:'}">${row.suttle}</c:if>
            </td>
            <td nowrap="nowrap" align="right">
                <c:if test="${row.heatname=='小计:'}">
                    <strong><font  color="red"><fmt:formatNumber
                    value="${row.suttlesj}" pattern="#,###,##0.0##" minFractionDigits="3"/></font></strong>
                </c:if>
                <c:if test="${row.heatname!='小计:'}"><fmt:formatNumber
                    value="${row.suttlesj}" pattern="#,###,##0.0##" minFractionDigits="3"/></c:if>
            </td>
            <td nowrap="nowrap">
                <fmt:formatDate value="${row.suttletime}" pattern="yyyy-MM-dd HH:mm:ss"/>
            </td>
          <td nowrap="nowrap" align="right">
                <c:if test="${row.heatname=='小计:'}">
                    <strong><font  color="red"><fmt:formatNumber
                    value="${row.headsuttle}" pattern="#,###,##0.0##" minFractionDigits="3"/></font></strong>
                </c:if>
                <c:if test="${row.heatname!='小计:'}"><fmt:formatNumber
                    value="${row.headsuttle}" pattern="#,###,##0.0##" minFractionDigits="3"/></c:if>
            </td>
        </tr>
    </c:forEach>
    <c:if test="${empty list}">
        <tr align="center">
            <td colspan="21" style="height:120px;font-size:16pt;text-align:center;vertical-align:middle">没有数据</td>
        </tr>
    </c:if>
    </tbody>
</table>
</body>
</html>
服务端(方法二)
  1. extField.java
public class TextField {
    //common properties
    private String columnName;
    private String fieldName;
    private String pattern;//显示格式

    //excel properties
    private int xls_columnView;
    //pdf properties
    private float width;
    private float height;
    private float horizontalAlignment;
    private float verticalAlignment;
    private float pdf_columnWidth = 0.2f;

    public TextField() {
    }

    public TextField(String fieldName) {
        this.fieldName = fieldName;
    }

    public TextField(String columnName, String fieldName) {
        this.columnName = columnName;
        this.fieldName = fieldName;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public float getHorizontalAlignment() {
        return horizontalAlignment;
    }

    public void setHorizontalAlignment(float horizontalAlignment) {
        this.horizontalAlignment = horizontalAlignment;
    }

    public float getVerticalAlignment() {
        return verticalAlignment;
    }

    public void setVerticalAlignment(float verticalAlignment) {
        this.verticalAlignment = verticalAlignment;
    }

    public int getXls_columnView() {
        return xls_columnView;
    }

    public void setXls_columnView(int xls_columnView) {
        this.xls_columnView = xls_columnView;
    }

    public float getPdf_columnWidth() {
        return pdf_columnWidth;
    }

    public void setPdf_columnWidth(float pdf_columnWidth) {
        this.pdf_columnWidth = pdf_columnWidth;
    }
}

  1. ReportTemplate.java
public class ReportTemplate {
    private static final Logger logger = Logger.getLogger(ReportTemplate.class);
    //文档元素
    private String title = "";
    private String pageHeader = "";
    private String pageFooter = "";
    private List<?> columnHeader;
    private List<?> columnFooter;
    private List<?> detail;
    private String lastPageFooter = "";
    private String summary;
    private float[] relativeWidths;
    private List<?> fieldList;

    public List<?> getFieldList() {
        return fieldList;
    }

    public void setFieldList(List<?> fieldList) {
        this.fieldList = fieldList;
    }
    //输出流
    private OutputStream outputStream;

    //构造函数

    //构造函数

    public ReportTemplate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        setPageFooter("制表人:____________" + "制表时间:" + df.format(new Date()));
    }

    public ReportTemplate(String name) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        setPageFooter("制表人:"+ name + "制表时间:" + df.format(new Date()));
    }

    public float[] getRelativeWidths() {
        return relativeWidths;
    }

    public void setRelativeWidths(float[] relativeWidths) {
        this.relativeWidths = relativeWidths;
    }

    // getter方法和setter方法

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPageHeader() {
        return pageHeader;
    }

    public void setPageHeader(String pageHeader) {
        this.pageHeader = pageHeader;
    }

    public String getPageFooter() {
        return pageFooter;
    }

    public void setPageFooter(String pageFooter) {
        this.pageFooter = pageFooter;
    }

    public List<?> getColumnHeader() {
        return columnHeader;
    }

    public void setColumnHeader(List<?> columnHeader) {
        this.columnHeader = columnHeader;
    }

    public List<?> getColumnFooter() {
        return columnFooter;
    }

    public void setColumnFooter(List<String> columnFooter) {
        this.columnFooter = columnFooter;
    }

    public List<?> getDetail() {
        return detail;
    }

    public void setDetail(List<?> detail) {
        this.detail = detail;
    }

    public String getLastPageFooter() {
        return lastPageFooter;
    }

    public void setLastPageFooter(String lastPageFooter) {
        this.lastPageFooter = lastPageFooter;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream out) {
        this.outputStream = out;
    }

    /**
     * 生成Excel文件
     */
    public void generateExcel() {
        logger.info("导出Excel报表=============");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 创建Excel文件、工作簿
            WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
            WritableSheet sheet = workbook.createSheet(getTitle(), 0);
            // 设置字体格式
            WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableFont contentFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat titleWCF = new WritableCellFormat(titleFont);
            WritableCellFormat headerWCF = new WritableCellFormat(contentFont);
            WritableCellFormat contentWCF = new WritableCellFormat(contentFont);
            contentWCF.setBorder(Border.ALL, BorderLineStyle.THIN);
            // 标题、页眉(首页)
            Label label = new Label(2, 0, getTitle(), titleWCF);
            sheet.addCell(label);
            label = new Label(0, 1, getPageHeader(), headerWCF);
            sheet.addCell(label);
            label = new Label(0, 2, getPageFooter(), headerWCF);
            sheet.addCell(label);
            // 主体内容
            if (getDetail() != null && getColumnHeader() != null) {
                sheet.setRowView(3, 400);
                for (int i = 0; i < getColumnHeader().size(); i++) {
                    sheet.setColumnView(i, 16);
                    label = new Label(i, 3, (String) getColumnHeader().get(i), contentWCF);
                    sheet.addCell(label);
                }
                WritableCellFormat[] numberWCF = new WritableCellFormat[fieldList.size()];
                for (int i = 0; i < fieldList.size(); i++) {
                    if (getDetail().size() > 0) {
                        Object obj = getDetail().get(0);
                        Class<?> aClass = obj.getClass();
                        TextField field = (TextField) fieldList.get(i);
                        String fieldType = aClass.getDeclaredField(field.getFieldName()).getType().getSimpleName();
                        if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("float") || fieldType.equalsIgnoreCase("double")) {
                            if (field.getPattern() != null) {
                                NumberFormat numberFormat = new NumberFormat(field.getPattern());
                                WritableCellFormat numberCellFormat = new WritableCellFormat(numberFormat);
                                numberCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
                                numberCellFormat.setFont(contentFont);
                                numberWCF[i] = numberCellFormat;
                            } else {
                                WritableCellFormat numberCellFormat = new WritableCellFormat();
                                numberCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
                                numberCellFormat.setFont(contentFont);
                                numberWCF[i] = numberCellFormat;
                            }
                        }
                    }
                }
                for (int i = 0; i < getDetail().size(); i++) {
                    sheet.setRowView(i + 4, 400);
                    Object obj = getDetail().get(i);
                    Class<?> aClass = obj.getClass();
                    for (int j = 0; j < fieldList.size(); j++) {
                        sheet.setColumnView(j, 16);
                        TextField field = (TextField) fieldList.get(j);
                        Object fieldObj = ReflectUtil.getFieldValue(field.getFieldName(), obj);
                        String fieldType = aClass.getDeclaredField(field.getFieldName()).getType().getSimpleName();
                        if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("float") || fieldType.equalsIgnoreCase("double")) {
                            double data = new BigDecimal(fieldObj.toString()).doubleValue();
                            jxl.write.Number numberLabel = new jxl.write.Number(j, i + 4, data, numberWCF[j]);
                            sheet.addCell(numberLabel);
                        } else {
                            String fieldValue = null;
                            if (fieldType.equalsIgnoreCase("Date")) {
                                fieldValue = fieldObj == null ? null : dateFormat.format(fieldObj);
                            } else {
                                fieldValue = fieldObj == null ? null : fieldObj.toString();
                            }
                            label = new Label(j, i + 4, fieldValue, contentWCF);
                            sheet.addCell(label);
                        }
                    }
                }
            }
            // 汇总语句
            if (getSummary() != null) {
                label = new Label(0, sheet.getRows(), getSummary(), headerWCF);
                sheet.addCell(label);
            }
            for (int i = 0; i < fieldList.size(); i++) {
                TextField field = (TextField) fieldList.get(i);
                if (field.getXls_columnView() > 0) {
                    sheet.setColumnView(i, field.getXls_columnView());
                }
            }
            workbook.write(); // 写入文件
            workbook.close();
            outputStream.close(); // 关闭流
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 生成Pdf文件
     */

    public void generatePdf() {
        logger.info("导出PDF报表=============");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Document document = new Document(PageSize.A3, 10, 10, 20, 170);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            PdfWriter.getInstance(document, byteArrayOutputStream);
            //中文支持
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //字体格式
            com.lowagie.text.Font contentFont = new com.lowagie.text.Font(baseFont, 10, com.lowagie.text.Font.NORMAL);
            com.lowagie.text.Font titleFont = new com.lowagie.text.Font(baseFont, 16, com.lowagie.text.Font.BOLD);
            com.lowagie.text.Font headerFont = new com.lowagie.text.Font(baseFont, 12, com.lowagie.text.Font.BOLD);
            //设置每页显示的页眉页脚,页码
            HeaderFooter footer = new HeaderFooter(new Phrase("页码: ", contentFont), true);
            footer.setBorder(Rectangle.NO_BORDER);
            footer.setAlignment(1);
            document.setFooter(footer);
            document.open();
            //设置标题
            Paragraph titleParagragh = new Paragraph(getTitle(), titleFont);
            titleParagragh.setAlignment(1);
            document.add(titleParagragh);
            //设置页眉(首页)
            Paragraph headerParagraph = new Paragraph(getPageHeader(), headerFont);
            headerParagraph.setAlignment(1);
            document.add(headerParagraph);
            //主体内容
            if (getDetail() != null && getColumnHeader() != null) {
                int size = fieldList.size();
                PdfPTable table = new PdfPTable(size);
                //设置 table 单元格宽度,好像不起作用
                if (relativeWidths != null && relativeWidths.length == size)
                    table.setWidths(relativeWidths);
                //生成表格内容
                table.setWidthPercentage(90);
                //设置列名占1行
                table.setHeaderRows(1);
                for (int i = 0; i < getColumnHeader().size(); i++) {
                    Paragraph para = new Paragraph((String) getColumnHeader().get(i), contentFont);
                    para.setAlignment(PdfPCell.ALIGN_CENTER);
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(para);
                    table.addCell(cell);
                }
                DecimalFormat[] decimalFormat = new DecimalFormat[fieldList.size()];
                for (int i = 0; i < fieldList.size(); i++) {
                    if (getDetail().size() > 0) {
                        Object obj = getDetail().get(0);
                        Class<?> aClass = obj.getClass();
                        TextField field = (TextField) fieldList.get(i);
                        String fieldType = aClass.getDeclaredField(field.getFieldName()).getType().getSimpleName();
                        if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("float") || fieldType.equalsIgnoreCase("double")) {
                            if (field.getPattern() != null) {
                                decimalFormat[i] = new DecimalFormat(field.getPattern());
                            } else {
                                decimalFormat[i] = new DecimalFormat();
                            }
                        }
                    }
                }
                for (int i = 0; i < getDetail().size(); i++) {
                    Object obj = getDetail().get(i);
                    Class<?> aClass = obj.getClass();
                    for (int j = 0; j < fieldList.size(); j++) {
                        TextField field = (TextField) fieldList.get(j);
                        Object fieldObj = ReflectUtil.getFieldValue(field.getFieldName(), obj);
                        String fieldType = aClass.getDeclaredField(field.getFieldName()).getType().getSimpleName();
                        if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("float") || fieldType.equalsIgnoreCase("double")) {
                            double data = new BigDecimal(fieldObj.toString()).doubleValue();
                            Paragraph para = new Paragraph(decimalFormat[j].format(data), contentFont);
                            para.setAlignment(PdfPCell.ALIGN_CENTER);
                            PdfPCell cell = new PdfPCell();
                            cell.addElement(para);
                            table.addCell(cell);
                        } else {
                            String fieldValue = null;
                            if (fieldType.equalsIgnoreCase("Date")) {
                                fieldValue = fieldObj == null ? null : dateFormat.format(fieldObj);
                            } else {
                                fieldValue = fieldObj == null ? null : fieldObj.toString();
                            }
                            Paragraph para = new Paragraph(fieldValue, contentFont);
                            para.setAlignment(PdfPCell.ALIGN_CENTER);
                            PdfPCell cell = new PdfPCell();
                            cell.addElement(para);
                            table.addCell(cell);
                        }
                    }
                }
                //汇总语句放到table末行
                if (getSummary() != null) {
                    PdfPCell sumCell = new PdfPCell();
                    sumCell.setColspan(size);
                    Paragraph sumParagraph = new Paragraph(getSummary(), headerFont);
                    sumParagraph.setAlignment(1);
                    sumCell.addElement(sumParagraph);
                    table.addCell(sumCell);
                }
                document.add(table);
                //设置页脚(末页)
                Paragraph footerParagraph = new Paragraph(getPageFooter(), headerFont);
                footerParagraph.setAlignment(1);
                document.add(footerParagraph);
                document.close();
                byteArrayOutputStream.writeTo(outputStream);
                outputStream.flush();
            }
        } catch (DocumentException de) {
            logger.error(de.getMessage(), de);
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

  1. controller
@RequestMapping("/excel")
public void excel(MSteelmeasureT measure, HttpServletResponse response)
    throws IOException
{

    List<MSteelmeasureT> reportList = smallSteelService.querysteelMeasure11(measure);
    MSteelmeasureT sum = smallSteelService.getSumMeasure(measure);
    String sumStr = "总计:" + sum.getCounts() + "捆,总重:" + sum.getWeight() + "吨";
    List<String> columnList = new ArrayList<String>();
    List fieldList = new ArrayList();

    columnList.add("批号");
    TextField textField = new TextField("heatsequence");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("计量ID");
    textField = new TextField("matchid");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("支数");
    textField = new TextField("xh");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("捆号");
    textField = new TextField("hookno");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("品名");
    textField = new TextField("materialname");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("规格");
    textField = new TextField("materialspec");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("钢号");
    textField = new TextField("steelsizename");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    columnList.add("尺寸");
    textField = new TextField("steellength");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("班名");
    textField = new TextField("createname");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("班次");
    textField = new TextField("classname");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("重量");
    textField = new TextField("weight");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("理重");
    textField = new TextField("lizhong");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("计量衡器");
    textField = new TextField("clientname");
    textField.setPdf_columnWidth(0.06f);
    fieldList.add(textField);

    columnList.add("过磅时间");
    textField = new TextField("createdate");
    textField.setPdf_columnWidth(0.1f);
    fieldList.add(textField);

    ReportTemplate report = new ReportTemplate(new ControllerUtil().currentUser().getStrName());
    report.setTitle("小棒交库单明细");
    report.setColumnHeader(columnList);
    report.setFieldList(fieldList);
    report.setDetail(reportList);
    report.setPageHeader("统计时间:" + measure.getBegindate() + "至" + measure.getEnddate());
    report.setSummary(sumStr);
    report.setOutputStream(response.getOutputStream());

    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String filename = "小棒交库单明细" + dateFormat.format(date);
    filename = new String(filename.getBytes("GBK"), "ISO-8859-1");

    response.reset();// 清空输出流
    response.setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");// 设定输出文件头
    response.setContentType("application/msexcel");// 定义输出类型
    report.generateExcel();

}

jsp生成excel,excel源码规则

MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="***MY_BOUNDARY_LINE***"

--***MY_BOUNDARY_LINE***
Content-Type: text/html; charset="gbk"

<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel">

<head>
<xml>
<o:DocumentProperties>
<o:Author>Tester</o:Author>
<o:LastAuthor>XLS Test</o:LastAuthor>
<o:Created>2011/6/2 11:11:11</o:Created>
<o:LastSaved>2011/6/2 11:11:11</o:LastSaved>
<o:Company>XLS Tester</o:Company>
<o:Version>1.0</o:Version>
</o:DocumentProperties>
</xml>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>MySheet1</x:Name>
<x:WorksheetSource HRef="cid:1"/>
</x:ExcelWorksheet>
<x:ExcelWorksheet>
<x:Name>MySheet2</x:Name>
<x:WorksheetSource HRef="cid:2"/>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>
</html>

--***MY_BOUNDARY_LINE***
Content-ID: 1
Content-Type: text/html; charset="big5"

<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel">

<head><meta http-equiv="Content-Type" content="text/html; charset=big5">
<xml>
<x:WorksheetOptions>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</xml>
</head>
<body>
<table cellspacing="0" border="1" id="SheetTable1" style="border-collapse:collapse;">
    <tr>
  <td>Index</td><td>BIG5</td>
    </tr><tr>
  <td>0</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>1</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>2</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>3</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>4</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>5</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>6</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>7</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>8</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr><tr>
  <td>9</td><td>2011/6/2 ノめ盞絏恨瞶 11:11:11</td>
    </tr>
</table></body>
</html>

--***MY_BOUNDARY_LINE***
Content-ID: 2
Content-Type: text/html; charset="gbk"

<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel">

<head><meta http-equiv="Content-Type" content="text/html; charset=gbk">
<xml>
<x:WorksheetOptions>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</xml>
</head>
<body>
<table cellspacing="0" border="1" id="SheetTable2" style="border-collapse:collapse;">
    <tr>
  <td>Index</td><td>BGK</td>
    </tr><tr>
  <td>0</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>1</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>2</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>3</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>4</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>5</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>6</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>7</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>8</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr><tr>
  <td>9</td><td>2011/6/2 用户密码管理 11:11:11</td>
    </tr>
</table></body>
</html>

--***MY_BOUNDARY_LINE***--

from wuhu src/main/webapp/WEB-INF/views/ironmeasure/toexcel.jsp

原文地址:https://www.cnblogs.com/zhuxiang1633/p/13177596.html