Java 如何在displaytag中导出扩展名为xlsx的excel文件

Java 如何在displaytag中导出扩展名为xlsx的excel文件,java,excel,export-to-excel,displaytag,Java,Excel,Export To Excel,Displaytag,我们使用了displaytag来导出xls格式的文件,但是我想要xlsx格式的文件。有没有办法将excel文件转换为新格式 我将显示标签中的扩展名从xls更改为xlsx <display:setProperty name="export.excel" value="true"/> <display:setProperty name="export.excel.filename" value="assignedUserGroup.xlsx" /> 但当我在Office

我们使用了displaytag来导出xls格式的文件,但是我想要xlsx格式的文件。有没有办法将excel文件转换为新格式

我将显示标签中的扩展名从xls更改为xlsx

<display:setProperty name="export.excel" value="true"/>
<display:setProperty name="export.excel.filename" value="assignedUserGroup.xlsx" />


但当我在Office2007或2010中打开它时,它给了我一个“文件扩展名无效”的问题。

这是一个非常有用的问题

步骤1:制作一个包
com.displaytag.export.views

步骤2:在上面的包中创建一个类
myExcel2007ExportView.java

步骤3:复制并粘贴以下代码到该文件中

package com.displaytag.export.views;


import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.servlet.jsp.JspException;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.displaytag.export.BinaryExportView;
import org.displaytag.model.Column;
import org.displaytag.model.ColumnIterator;
import org.displaytag.model.HeaderCell;
import org.displaytag.model.RowIterator;
import org.displaytag.model.TableModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.lowagie.text.BadElementException;

public class myExcel2007ExportView implements BinaryExportView{

 //private static Log log = LogFactory.getLog(myExcel2007ExportView.class);
private TableModel model;
private boolean exportFull;
private boolean header;
private boolean decorated;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private int rowCount=0;
private CellStyle normalstyle=null;
private CellStyle headerstyle=null;
private CellStyle captionstyle=null;

private XSSFFont defaultFont;
private XSSFFont headerFont;
private XSSFFont captionFont;

public String getMimeType() {
     return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}

public void setParameters(TableModel tableModel, boolean exportFullList, boolean includeHeader,
       boolean decorateValues)
{
   this.model = tableModel;
   this.exportFull = true;
   this.header = includeHeader;
   this.decorated = decorateValues;
}

public boolean outputPage() {
    return false;
}

protected void initTable() throws BadElementException
{
    //Blank workbook
    workbook = new XSSFWorkbook();
     
    //Create a blank sheet
    sheet = workbook.createSheet("Server Management System");
    
    
    defaultFont= workbook.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    headerFont= workbook.createFont();
    headerFont.setFontHeightInPoints((short)10);
    headerFont.setFontName("Arial");
    headerFont.setColor(IndexedColors.WHITE.getIndex());
    headerFont.setBold(true);
    headerFont.setItalic(false);
    
    captionFont= workbook.createFont();
    captionFont.setFontHeightInPoints((short)15);
    captionFont.setFontName("Arial");
    captionFont.setColor(IndexedColors.BLACK.getIndex());
    captionFont.setBold(true);
    captionFont.setItalic(false);
    
    
    normalstyle= workbook.createCellStyle(); 
    normalstyle.setFillBackgroundColor(IndexedColors.WHITE.getIndex());
    normalstyle.setFillPattern(CellStyle.BIG_SPOTS);
    normalstyle.setAlignment(CellStyle.ALIGN_CENTER);
    normalstyle.setFont(defaultFont);
    
    headerstyle= workbook.createCellStyle(); 
    headerstyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    headerstyle.setFillPattern(CellStyle.BIG_SPOTS);
    headerstyle.setAlignment(CellStyle.ALIGN_CENTER);
    headerstyle.setFont(headerFont);
    
    captionstyle= workbook.createCellStyle(); 
    captionstyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    captionstyle.setFillPattern(CellStyle.BIG_SPOTS);
    captionstyle.setAlignment(CellStyle.ALIGN_CENTER);
    captionstyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    captionstyle.setFont(captionFont);
    
}

protected void generateXLSXTable() throws JspException, BadElementException
{
    //adding caption
    if(this.model.getCaption()!=null && this.model.getCaption()!="")
    {
     Row blankrow = sheet.createRow(rowCount++);
     Row row = sheet.createRow(rowCount++);
     
     row.setHeight((short)5000);
     int columnCount=0;
     Cell captionCell = row.createCell(columnCount++);
     captionCell.setCellValue(this.model.getCaption());
     captionCell.setCellStyle(captionstyle);
     sheet.addMergedRegion(new CellRangeAddress(
             rowCount-1, //first row (0-based)
             rowCount-1, //last row  (0-based)
             columnCount-1, //first column (0-based)
             columnCount+5  //last column  (0-based)
     ));
     Row blankrow2 = sheet.createRow(rowCount++);
    }
    
    if (this.header)
    {
        generateHeaders();
    }
    
    generateRows();
    
    //adding footer
    if(this.model.getFooter()!=null && this.model.getFooter()!="")
    {
     Row blankrow = sheet.createRow(rowCount++);
     Row blankrow2 = sheet.createRow(rowCount++);
     Row row = sheet.createRow(rowCount++);
     
     row.setHeight((short)1000);
     int columnCount=0;
     Cell captionCell = row.createCell(columnCount++);
     captionCell.setCellValue(this.model.getFooter());
     captionCell.setCellStyle(captionstyle);
     sheet.addMergedRegion(new CellRangeAddress(
             rowCount-1, //first row (0-based)
             rowCount-1, //last row  (0-based)
             columnCount-1, //first column (0-based)
             columnCount+5  //last column  (0-based)
     ));
    }
}

protected void generateHeaders() throws BadElementException
{
    Iterator<HeaderCell> iterator = this.model.getHeaderCellList().iterator();
    Row row = sheet.createRow(rowCount++);
    
    int columnCount=0;
    while (iterator.hasNext())
    {
        sheet.autoSizeColumn(columnCount);
        HeaderCell headerCell = iterator.next();

        String columnHeader = headerCell.getTitle();

        if (columnHeader == null)
        {
            columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
        }

        Cell hdrCell = row.createCell(columnCount++);
        hdrCell.setCellValue(columnHeader);
        hdrCell.setCellStyle(headerstyle);
    }
}

protected void generateRows() throws JspException, BadElementException
{
    // get the correct iterator (full or partial list according to the exportFull field)
    RowIterator rowIterator = this.model.getRowIterator(this.exportFull);
    // iterator on rows
    while (rowIterator.hasNext())
    {
        Row newrow = sheet.createRow(rowCount++);
        org.displaytag.model.Row row = rowIterator.next();
        // iterator on columns
        ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList());
        int columnCount=0;
        while (columnIterator.hasNext())
        {
            Column column = columnIterator.nextColumn();

            // Get the value to be displayed for the column
            Object value = column.getValue(this.decorated);

            Cell Cell = newrow.createCell(columnCount++);
            Cell.setCellValue(ObjectUtils.toString(value));
        }
    }
    
}

@Override
public void doExport(OutputStream out) throws IOException, JspException {
    
    try {
        // Initialize the table with the appropriate number of columns
        initTable();
        
        generateXLSXTable();
        
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
           
    workbook.write(out);
    out.close();
}
}
注意:确保不更改属性的顺序

第6步:
jsp
文件中

 <display:table id="l" name="yourList" pagesize="10" requestURI="/yourAction.action" style="width:100%" export="true">
                            
    
<display:setProperty name="export.csv.filename" value="YourReport.csv" />
<display:setProperty name="export.excel.filename" value="YourReport.xls" />
<display:setProperty name="export.xml.filename" value="YourReport.xml" />
<display:setProperty name="export.rtf.filename" value="YourReport.rtf" />
<display:setProperty name="export.pdf.filename" value="YourReport.pdf" />
<display:setProperty name="export.[mymedia].filename" value="YourReport.xlsx" />
                    
                
<display:caption media="csv xml excel pdf rtf [mymedia]"> yourcaption</display:caption>
                            
<display:column property="id" titleKey="selectlogdetails.logid"  sortable="false" />
//other columns
                        
<display:footer media="csv xml excel pdf rtf [mymedia]"> yourfooter
</display:footer>
</display:table>

你的说明
//其他栏目
你的脚
注意:不要忘记在标题、页脚中添加[mymedia],也不要忘记如下设置文件名。

 <display:setProperty name="export.[mymedia].filename" value="YourReport.xlsx" />

第7步:
WEB-INF/lib
文件夹中复制并粘贴以下
jar
文件

displaytag-1.2.jar

displaytag-export-poi-1.2.jar

displaytag-portlet-1.2.jar

commons-lang-2.3或以上

commons-beanutils-1.7.0或以上

commons-collections-3.1或更高版本

commons-logging-1.1.jar

itext-1.3或更高版本

slf4j-api-1.4.2或以上

slf4j-log4j12-1.4.2或以上

poi-3.2-FINAL.jar

poi-3.9.jar

poi-ooxml-3.9.jar

poi-ooxml-schemas-3.9.jar

stax-api-1.0.1.jar

xmlbeans-2.6.0.jar

commons-codec-1.5.jar

dom4j-1.6.1.jar

log4j-1.2.15.jar

注意:如果我忘记了任何依赖项jar,请与maven核对。

 <display:setProperty name="export.[mymedia].filename" value="YourReport.xlsx" />
第8步:运行项目并享受:)如果有任何错误,请告诉我。另外,如果您在
displaytag
中使用任何装饰器,则必须为其编写代码

多谢各位

要创建资源文件夹,如果您使用eclipse,请右键单击java资源,如下所示

指定名称res并在其中创建属性文件

使用netBeans IDE 7.4


告诉我在哪里创建资源文件夹。我在默认包中创建了displaytag.properties文件,当我运行项目时,它会在路径为[/reportnguccGraph]的上下文中为Servlet[default]提供异常
severy:Servlet.service()抛出异常java.lang.IllegalStateException:cannotcall sendError()提交响应后
请参阅我的答案,了解如何创建resorce文件夹。我给创建的源文件夹命名为
res
,并将
displaytag.properties
文件放入其中。在
src
文件夹中有java文件,在
res
中我们放置了资源文件。我使用的是netbeans,我的displaytag.properties文件与其他xml文件在默认包中,就像你的一样,但是当响应到jspproject时它会给我一个异常,只有当我将displaytag.properties文件添加到src时才会给我一个异常文件夹。我仍然不知道如何将它添加到资源文件夹中,您希望我在src文件夹或其他源文件夹中创建一个简单的文件夹。异常为“严重:Servlet jsp的Servlet.service()引发异常java.lang.NullPointerException”