我可以使用 Apache-Poi 在流式模式下将 Excel 电子表格格式化为表格吗 [英] Can I use Apache-Poi to format Excel spreadsheet as a Table in Streaming Mode

查看:23
本文介绍了我可以使用 Apache-Poi 在流式模式下将 Excel 电子表格格式化为表格吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过选择数据和ctrl + T可以将Excel中的常规电子表格(选项卡)制成表格.(这为每一列提供了一个允许过滤值的标题).

我的电子表格是使用 Apache POI 和 SXSSF 流接口创建的,我必须使用流接口因为电子表格可能非常大.是否可以通过编程将每个工作表变成表格?

我遇到了 XSSFTable 类,但不清楚如何使用它或是否可以在流模式下使用.

package com.jthink.songkong.reports.spreadsheet;导入 com.jthink.songkong.db.SongCache;导入 com.jthink.songkong.text.SongFieldName;导入 com.jthink.songkong.ui.MainWindow;导入 com.jthink.songlayer.*;导入 org.apache.poi.ss.usermodel.*;导入 org.apache.poi.xssf.streaming.SXSSFSheet;导入 org.apache.poi.xssf.streaming.SXSSFWorkbook;导入 org.hibernate.Session;导入 java.io.FileOutputStream;导入 java.io.IOException;导入 java.util.ArrayList;导入 java.util.HashMap;导入 java.util.List;导入 java.util.Map;/*** 由 Paul 于 2017 年 9 月 3 日创建.*/公共类电子表格报告{//我们想在字符中使用的最大宽度,无论数据如何公共静态最终 int MAX_COL_WIDTH = 100;public static final int COL_WIDTH_MULTIPLIER = 256;私有静态最终 int FLUSH_SIZE = 1000;public static final int FONT_MARGIN_OF_ERROR = 5;私人字符串报告名称;私有 FileOutputStream fos;私人 int rowCounter =0;私人 SXSSFWorkbook 工作簿;私人 CellStyle headerStyle;私有 CellStyle 字段AddedStyle;私人 CellStyle fieldChangedStyle;私有 CellStyle 字段DeletedStyle;私有 CellStyle 字段UnchangedStyle;私人列表<工作表>工作表;私有 CreationHelper 工厂;public SpreadsheetReport(String reportName) 抛出 IOException{this.reportName =reportName;//创建新文件fos = new FileOutputStream(reportName);工作簿=新的SXSSF工作簿(FLUSH_SIZE);factory = workbook.getCreationHelper();worksheets = new ArrayList();worksheets.add(0, new BasicWorksheet(workbook));worksheets.add(1, new ReleaseWorksheet(workbook));worksheets.add(2, new ClassicalWorksheet(workbook));worksheets.add(3, new PeopleWorksheet(workbook));worksheets.add(4, new SortWorksheet(workbook));worksheets.add(5, new MusicBrainzWorksheet(workbook));worksheets.add(6, new MusicBrainzWorkWorksheet(workbook));worksheets.add(7, new AcousticBrainzWorksheet(workbook));字体 font = workbook.createFont();font.setBold(true);headerStyle = workbook.createCellStyle();headerStyle.setFont(font);headerStyle.setWrapText(true);fieldAddedStyle = workbook.createCellStyle();fieldAddedStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());fieldAddedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);fieldAddedStyle.setWrapText(true);fieldChangedStyle = workbook.createCellStyle();fieldChangedStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());fieldChangedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);fieldChangedStyle.setWrapText(true);fieldDeletedStyle = workbook.createCellStyle();fieldDeletedStyle.setFillForegroundColor(IndexedColors.RED.getIndex());fieldDeletedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);fieldDeletedStyle.setWrapText(true);fieldUnchangedStyle = workbook.createCellStyle();fieldUnchangedStyle.setWrapText(true);}public void writeHeader() 抛出 IOException{for(工作表下一个:工作表){行 r = next.getSheet().createRow(rowCounter);for(int i=0;i  songChanges) 抛出 IOException{for(工作表下一个:工作表){行 r = next.getSheet().createRow(rowCounter);org.apache.poi.ss.usermodel.Cell c ;c=r.createCell(0);c.setCellValue(song.getFilename());MapfieldToChanges = new HashMap();for(SongChanges nextChange:songChanges){fieldToChanges.put(nextChange.getField(), nextChange);}for (int i = 0; i < next.getMapping().size(); i++){addFieldValue(session, next , r, i, next.getMapping().get(i), fieldToChanges.get(next.getMapping().get(i).getSongFieldName().getSongFieldKey()), song);}}行计数器++;}/*** 将旧值显示为注释/ttoltip* @param r* @param c* @参数表* @参数值*/private void addCellComment(Row r, Cell c, Worksheet sheet, String value){String formattedValue = value.replace('\u0000', '\n');int rowCount = value.split("\\\\u000").length;ClientAnchor 锚点 = factory.createClientAnchor();anchor.setCol1(c.getColumnIndex());//文件名列更宽if(c.getColumnIndex()==0){anchor.setCol2(c.getColumnIndex()+5);}别的{anchor.setCol2(c.getColumnIndex()+2);}anchor.setRow1(r.getRowNum());anchor.setRow2(r.getRowNum()+rowCount);//创建评论并设置文本+作者绘图绘图 = sheet.getDrawing();评论 comment = drawing.createCellComment(anchor);RichTextString str = factory.createRichTextString(formattedValue);评论.setString(str);c.setCellComment(评论);}private void addFieldValue(Session session, Worksheet sheet, Row r, int电子表格索引, SongFieldNameColumnWidth sfncw, SongChanges fieldChanges, Song song){SongFieldName 歌曲FieldName = sfncw.getSongFieldName();字符串值 = "";org.apache.poi.ss.usermodel.Cell c ;c=r.createCell(spreadsheetIndex);//对该字段进行了更改if(fieldChanges!=null){SongChangeType changeType = fieldChanges.getType();if(songFieldName==SongFieldName.FILENAME){value = fieldChanges.getNewValue();c.setCellValue(value);c.setCellStyle(fieldChangedStyle);//addCellComment(r, c, sheet, song.getFilename());}else if(songFieldName==SongFieldName.COVER_ART){if (changeType == SongChangeType.ADD ){CoverImage ci = SongCache.findCoverImageByDataKey(session, fieldChanges.getNewValue());如果(ci!=空){值 = ci.getWidth() + "x"+ ci.getHeight();c.setCellValue(value);c.setCellStyle(fieldAddedStyle);}别的{MainWindow.logger.severe("无法找到歌曲的封面图片:"+song.getRecNo()+":"+song.getFilename());}session.flush();}否则如果(changeType == SongChangeType.EDIT){CoverImage ci = SongCache.findCoverImageByDataKey(session, fieldChanges.getNewValue());如果(ci!=空){值 = ci.getWidth() + "x"+ ci.getHeight();c.setCellValue(value);c.setCellStyle(fieldChangedStyle);}别的{MainWindow.logger.severe("无法找到歌曲的封面图片:"+song.getRecNo()+":"+song.getFilename());}CoverImage ciOrig = SongCache.findCoverImageByDataKey(session, fieldChanges.getOriginalValue());如果(ciOrig!=空){String valueOrig = ciOrig.getWidth() + "x"+ ciOrig.getHeight();//addCellComment(r, c, sheet, valueOrig);}session.flush();}else if (changeType == SongChangeType.NOCHANGE){CoverArt coverart = song.getCoverArts().get(0);value = coverart.getCoverImage().getWidth()+";x"+ coverart.getCoverImage().getHeight();c.setCellValue(value);c.setCellStyle(fieldUnchangedStyle);}else if (changeType == SongChangeType.DELETE){c.setCellStyle(fieldDeletedStyle);}}别的{if (changeType == SongChangeType.ADD){value = fieldChanges.getNewValue().replace('\u0000', '\n');c.setCellValue(value);c.setCellStyle(fieldAddedStyle);}否则如果(changeType == SongChangeType.EDIT){value = fieldChanges.getNewValue().replace('\u0000', '\n');c.setCellValue(value);c.setCellStyle(fieldChangedStyle);//addCellComment(r, c, sheet, fieldChanges.getOriginalValue());}else if (changeType == SongChangeType.DELETE){c.setCellStyle(fieldDeletedStyle);}else if (changeType == SongChangeType.NOCHANGE){value = fieldChanges.getOriginalValue().replace('\u0000', '\n');c.setCellValue(value);c.setCellStyle(fieldUnchangedStyle);//addCellComment(r, c, sheet, fieldChanges.getOriginalValue());}}}//字段不变//注意不应该被调用,因为我们现在也记录未更改的字段别的{if(songFieldName==SongFieldName.FILENAME){值 = 歌曲.getFilename();c.setCellValue(value);}else if(songFieldName==SongFieldName.COVER_ART){if(song.getCoverArts().size()>0){CoverArt coverart = song.getCoverArts().get(0);value = coverart.getCoverImage().getWidth()+";x"+ coverart.getCoverImage().getHeight();c.setCellValue(value);}}别的{value = song.getFieldValueOrEmptyString(songFieldName.getSongFieldKey()).replace('\u0000', '\n');c.setCellStyle(fieldUnchangedStyle);c.setCellValue(value);}}sfncw.setColumnWidthFromValue(value);}public void finish() 抛出 IOException{for(工作表下一个:工作表){SXSSFSheet 表 = (SXSSFSheet)next.getSheet();for (int i = 0; i < next.getMapping().size(); i++){int columnWidth = next.getMapping().get(i).getColumnWidthFromValue() + FONT_MARGIN_OF_ERROR;columnWidth = columnWidth >MAX_COL_WIDTH ?MAX_COL_WIDTH :列宽;sheet.setColumnWidth(i, columnWidth * COL_WIDTH_MULTIPLIER);}}工作簿.写(fos);fos.close();工作簿.处置();}}

解决方案

刚刚发现 xlsx 格式只是将一系列 Xml 文件压缩成一个 zip 文件.因此,如果我尝试在 Excel 中手动为工作表创建一个表格,保存更改,重命名为 zip 并解压缩,然后发现它创建了一个 xl/tables/table1.xml 以配合 xl/worksheets/sheet1.xml

它包括以下内容

<autoFilter ref="A1:M13"/><tableColumns count="13"><tableColumn id="1" name="文件名"/><tableColumn id="2" name="艺术家" dataDxfId="12"/><tableColumn id="3" name="Disc No" dataDxfId="11"/><tableColumn id="4" name="Track No" dataDxfId="10"/><tableColumn id="5" name="Single Disc TrackNo" dataDxfId="9"/><tableColumn id="6" name="Title" dataDxfId="8"/><tableColumn id="7" name="专辑艺术家" dataDxfId="7"/><tableColumn id="8" name="相册" dataDxfId="6"/><tableColumn id="9" name="艺术品"/><tableColumn id="10" name="Year" dataDxfId="5"/><tableColumn id="11" name="原始发行年份" dataDxfId="4"/><tableColumn id="12" name="流派" dataDxfId="3"/><tableColumn id="13" name="分组" dataDxfId="2"/></tableColumns><tableStyleInfo name="TableStyleMedium2" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/>

Sheet1.xml 包含

<dimension ref="A1:M13"/><工作表视图><sheetView tabSelected="1" workbookViewId="0"><selection activeCell="A6" sqref="A6"/></sheetView></sheetViews><sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/><cols><col min="1" max="1" width="69" customWidth="1"/><col min="2" max="2" width="20" customWidth="1"/><col min="3" max="3" width="12" customWidth="1"/><col min="4" max="4" width="13" customWidth="1"/><col min="5" max="5" width="24" customWidth="1"/><col min="6" max="6" width="32" customWidth="1"/><col min="7" max="7" width="18" customWidth="1"/><col min="8" max="8" width="23" customWidth="1"/><col min="9" max="9" width="13" customWidth="1"/><col min="10" max="10" width="9" customWidth="1"/><col min="11" max="11" width="26" customWidth="1"/><col min="12" max="12" width="36" customWidth="1"/><col min="13" max="13" width="13" customWidth="1"/></cols><工作表数据><row r="1" spans="1:13" x14ac:dyDescent="0.25"><c r="A1" s="1" t="s"><v>0</v></c><c r="B1" s="1" t="s"><v>1</v></c><c r="C1" s="1" t="s"><v>2</v></c>………………………………………………………………………………………………………………………………………………………………………………………………………………<c r="M13" s="3" t="s"><v>22</v></c></row></sheetData><pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/><tableParts count="1"><tablePart r:id="rId1"/></tableParts>

因此可以通过解析关联的工作表或在我的情况下创建表格,因为我首先创建工作表我拥有创建表格 xml 文件所需的信息,并将它们添加到 zip.

可能可以独立使用 pois XSSFTable 类(它有一个公共构造函数),然后将其渲染到 Xml,不确定.

A regular spreadsheet (tab) in Excel can be made into a table by selecting the data and ctrl + T. (This gives each column a header that allows filtering of values).

My spreadsheets are created using Apache POI and the SXSSF streaming interface, I have to use the streaming interface since the spreadsheet can be quite large. Is it possible to programmatically turn each sheet into a table?

I came across XSSFTable class but it's not clear how to use it or whether it can be used in streaming mode.

package com.jthink.songkong.reports.spreadsheet;

import com.jthink.songkong.db.SongCache;
import com.jthink.songkong.text.SongFieldName;
import com.jthink.songkong.ui.MainWindow;
import com.jthink.songlayer.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.hibernate.Session;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Paul on 09/03/2017.
 */
public class SpreadsheetReport
{
    //Max Width we want to use in chars, whatever the data
    public static final int MAX_COL_WIDTH = 100;

    public static final int COL_WIDTH_MULTIPLIER = 256;
    private static final int FLUSH_SIZE = 1000;
    public static final int FONT_MARGIN_OF_ERROR = 5;
    private String reportName;
    private FileOutputStream fos;
    private int rowCounter =0;
    private SXSSFWorkbook workbook;
    private CellStyle headerStyle;
    private CellStyle fieldAddedStyle;
    private CellStyle fieldChangedStyle;
    private CellStyle fieldDeletedStyle;
    private CellStyle fieldUnchangedStyle;
    private List<Worksheet> worksheets;
    private CreationHelper factory;

    public SpreadsheetReport(String reportName) throws IOException
    {
        this.reportName =reportName;
        //Create new File
        fos = new FileOutputStream(reportName);
        workbook = new SXSSFWorkbook(FLUSH_SIZE);


        factory = workbook.getCreationHelper();

        worksheets = new ArrayList<Worksheet>();
        worksheets.add(0, new BasicWorksheet(workbook));
        worksheets.add(1, new ReleaseWorksheet(workbook));
        worksheets.add(2, new ClassicalWorksheet(workbook));
        worksheets.add(3, new PeopleWorksheet(workbook));
        worksheets.add(4, new SortWorksheet(workbook));
        worksheets.add(5, new MusicBrainzWorksheet(workbook));
        worksheets.add(6, new MusicBrainzWorkWorksheet(workbook));
        worksheets.add(7, new AcousticBrainzWorksheet(workbook));


        Font font = workbook.createFont();
        font.setBold(true);
        headerStyle = workbook.createCellStyle();
        headerStyle.setFont(font);
        headerStyle.setWrapText(true);

        fieldAddedStyle = workbook.createCellStyle();
        fieldAddedStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
        fieldAddedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        fieldAddedStyle.setWrapText(true);

        fieldChangedStyle = workbook.createCellStyle();
        fieldChangedStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        fieldChangedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        fieldChangedStyle.setWrapText(true);

        fieldDeletedStyle = workbook.createCellStyle();
        fieldDeletedStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        fieldDeletedStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        fieldDeletedStyle.setWrapText(true);

        fieldUnchangedStyle = workbook.createCellStyle();
        fieldUnchangedStyle.setWrapText(true);
    }

    public void writeHeader() throws IOException
    {
        for(Worksheet next:worksheets)
        {
            Row   r = next.getSheet().createRow(rowCounter);
            for(int i=0;i <next.getMapping().size(); i++)
            {
                addHeaderCell(r, i, next.getMapping().get(i));
            }
        }
        rowCounter++;
    }

    private void addHeaderCell(Row r, int spreadsheetIndex, SongFieldNameColumnWidth field)
    {
        Cell cell  = r.createCell(spreadsheetIndex);
        cell.setCellValue(field.getSongFieldName().getName());
        cell.setCellStyle(headerStyle);
    }

    public void writeDatatoXlsFile(Session session, Song song, List<SongChanges> songChanges) throws IOException
    {
        for(Worksheet next:worksheets)
        {
            Row   r = next.getSheet().createRow(rowCounter);
            org.apache.poi.ss.usermodel.Cell c ;
            c=r.createCell(0);
            c.setCellValue(song.getFilename());

            Map<SongFieldKey, SongChanges> fieldToChanges = new HashMap<SongFieldKey, SongChanges>();
            for(SongChanges nextChange:songChanges)
            {
                fieldToChanges.put(nextChange.getField(), nextChange);
            }

            for (int i = 0; i < next.getMapping().size(); i++)
            {
                addFieldValue(session, next , r, i, next.getMapping().get(i), fieldToChanges.get(next.getMapping().get(i).getSongFieldName().getSongFieldKey()), song);
            }
        }
        rowCounter++;
    }

    /**
     * Show the old value as a comment/ttoltip
     * @param r
     * @param c
     * @param sheet
     * @param value
     */
    private void addCellComment(Row r, Cell c, Worksheet sheet, String value)
    {
        String formattedValue    =  value.replace('\u0000', '\n');
        int    rowCount         =  value.split("\\\\u000").length;
        ClientAnchor anchor = factory.createClientAnchor();
        anchor.setCol1(c.getColumnIndex());

        //Wider for filename column
        if(c.getColumnIndex()==0)
        {
            anchor.setCol2(c.getColumnIndex()+5);
        }
        else
        {
            anchor.setCol2(c.getColumnIndex()+2);
        }
        anchor.setRow1(r.getRowNum());
        anchor.setRow2(r.getRowNum()+rowCount);

        // Create the comment and set the text+author
        Drawing drawing = sheet.getDrawing();
        Comment comment = drawing.createCellComment(anchor);
        RichTextString str = factory.createRichTextString(formattedValue);
        comment.setString(str);
        c.setCellComment(comment);

    }
    private void addFieldValue(Session session, Worksheet sheet, Row r, int spreadsheetIndex, SongFieldNameColumnWidth sfncw, SongChanges fieldChanges, Song song)
    {
        SongFieldName   songFieldName = sfncw.getSongFieldName();
        String          value = "";
        org.apache.poi.ss.usermodel.Cell c ;
        c=r.createCell(spreadsheetIndex);

        //Chnanges have been made to this field
        if(fieldChanges!=null)
        {
            SongChangeType changeType = fieldChanges.getType();
            if(songFieldName==SongFieldName.FILENAME)
            {
                value = fieldChanges.getNewValue();
                c.setCellValue(value);
                c.setCellStyle(fieldChangedStyle);
                //addCellComment(r, c, sheet, song.getFilename());
            }
            else if(songFieldName==SongFieldName.COVER_ART)
            {
                if (changeType == SongChangeType.ADD )
                {
                    CoverImage ci = SongCache.findCoverImageByDataKey(session, fieldChanges.getNewValue());
                    if(ci!=null)
                    {
                        value = ci.getWidth() + " x " + ci.getHeight();
                        c.setCellValue(value);
                        c.setCellStyle(fieldAddedStyle);
                    }
                    else
                    {
                        MainWindow.logger.severe("Unable to find coverimage for song:"+song.getRecNo()+":"+song.getFilename());
                    }
                    session.flush();
                }
                else if (changeType == SongChangeType.EDIT)
                {
                    CoverImage ci = SongCache.findCoverImageByDataKey(session, fieldChanges.getNewValue());
                    if(ci!=null)
                    {
                        value = ci.getWidth() + " x " + ci.getHeight();
                        c.setCellValue(value);
                        c.setCellStyle(fieldChangedStyle);
                    }
                    else
                    {
                        MainWindow.logger.severe("Unable to find coverimage for song:"+song.getRecNo()+":"+song.getFilename());
                    }
                    CoverImage ciOrig = SongCache.findCoverImageByDataKey(session, fieldChanges.getOriginalValue());
                    if(ciOrig!=null)
                    {
                        String valueOrig = ciOrig.getWidth() + " x " + ciOrig.getHeight();
                        //addCellComment(r, c, sheet, valueOrig);
                    }
                    session.flush();
                }
                else if (changeType == SongChangeType.NOCHANGE)
                {
                    CoverArt coverart = song.getCoverArts().get(0);
                    value = coverart.getCoverImage().getWidth()+" x" + coverart.getCoverImage().getHeight();
                    c.setCellValue(value);
                    c.setCellStyle(fieldUnchangedStyle);
                }
                else if (changeType == SongChangeType.DELETE)
                {
                    c.setCellStyle(fieldDeletedStyle);
                }
            }
            else
            {
                if (changeType == SongChangeType.ADD)
                {
                    value = fieldChanges.getNewValue().replace('\u0000', '\n');
                    c.setCellValue(value);
                    c.setCellStyle(fieldAddedStyle);

                }
                else if (changeType == SongChangeType.EDIT)
                {
                    value = fieldChanges.getNewValue().replace('\u0000', '\n');
                    c.setCellValue(value);
                    c.setCellStyle(fieldChangedStyle);
                    //addCellComment(r, c, sheet, fieldChanges.getOriginalValue());
                }
                else if (changeType == SongChangeType.DELETE)
                {
                    c.setCellStyle(fieldDeletedStyle);
                }
                else if (changeType == SongChangeType.NOCHANGE)
                {
                    value = fieldChanges.getOriginalValue().replace('\u0000', '\n');
                    c.setCellValue(value);
                    c.setCellStyle(fieldUnchangedStyle);
                    //addCellComment(r, c, sheet, fieldChanges.getOriginalValue());
                }
            }
        }
        //Field is unchanged
        //Note shoud not be called because we now log unchanged fields as well
        else
        {
            if(songFieldName==SongFieldName.FILENAME)
            {
                value = song.getFilename();
                c.setCellValue(value);
            }
            else if(songFieldName==SongFieldName.COVER_ART)
            {
                if(song.getCoverArts().size()>0)
                {
                    CoverArt coverart = song.getCoverArts().get(0);
                    value = coverart.getCoverImage().getWidth()+" x" + coverart.getCoverImage().getHeight();
                    c.setCellValue(value);
                }
            }
            else
            {
                value = song.getFieldValueOrEmptyString(songFieldName.getSongFieldKey()).replace('\u0000', '\n');
                c.setCellStyle(fieldUnchangedStyle);
                c.setCellValue(value);
            }
        }
        sfncw.setColumnWidthFromValue(value);
    }

    public void finish() throws IOException
    {
        for (Worksheet next : worksheets)
        {
            SXSSFSheet sheet = (SXSSFSheet)next.getSheet();

            for (int i = 0; i < next.getMapping().size(); i++)
            {
                int columnWidth = next.getMapping().get(i).getColumnWidthFromValue() + FONT_MARGIN_OF_ERROR;
                columnWidth = columnWidth > MAX_COL_WIDTH ? MAX_COL_WIDTH : columnWidth;
                sheet.setColumnWidth(i, columnWidth * COL_WIDTH_MULTIPLIER);
            }
        }
        workbook.write(fos);
        fos.close();
        workbook.dispose();
    }

}

解决方案

Just found out that the xlsx format is simply a series of Xml files compressed into a single zip file. So if I tried creating a table manually within Excel for a worksheet, saving changes, renamed to zip and uncompressing and found it had a created a xl/tables/table1.xml to go with xl/worksheets/sheet1.xml

It consisted of the following

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table1" displayName="Table1" ref="A1:M13" totalsRowShown="0" headerRowDxfId="0" dataDxfId="1">
    <autoFilter ref="A1:M13"/><tableColumns count="13">
        <tableColumn id="1" name="Filename"/>
        <tableColumn id="2" name="Artist" dataDxfId="12"/>
        <tableColumn id="3" name="Disc No" dataDxfId="11"/>
        <tableColumn id="4" name="Track No" dataDxfId="10"/>
        <tableColumn id="5" name="Single Disc TrackNo" dataDxfId="9"/>
        <tableColumn id="6" name="Title" dataDxfId="8"/>
        <tableColumn id="7" name="Album Artist" dataDxfId="7"/>
        <tableColumn id="8" name="Album" dataDxfId="6"/>
        <tableColumn id="9" name="Artwork"/>
        <tableColumn id="10" name="Year" dataDxfId="5"/>
        <tableColumn id="11" name="Original Release Year" dataDxfId="4"/>
        <tableColumn id="12" name="Genre" dataDxfId="3"/>
        <tableColumn id="13" name="Grouping" dataDxfId="2"/>
        </tableColumns>
        <tableStyleInfo name="TableStyleMedium2" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/>
</table>

Sheet1.xml contains

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet 
    xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
    <dimension ref="A1:M13"/>
    <sheetViews>
        <sheetView tabSelected="1" workbookViewId="0">
            <selection activeCell="A6" sqref="A6"/>
        </sheetView>
    </sheetViews>
    <sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/>
        <cols>
            <col min="1" max="1" width="69" customWidth="1"/>
            <col min="2" max="2" width="20" customWidth="1"/>
            <col min="3" max="3" width="12" customWidth="1"/>
            <col min="4" max="4" width="13" customWidth="1"/>
            <col min="5" max="5" width="24" customWidth="1"/>
            <col min="6" max="6" width="32" customWidth="1"/>
            <col min="7" max="7" width="18" customWidth="1"/>
            <col min="8" max="8" width="23" customWidth="1"/>
            <col min="9" max="9" width="13" customWidth="1"/>
            <col min="10" max="10" width="9" customWidth="1"/>
            <col min="11" max="11" width="26" customWidth="1"/>
            <col min="12" max="12" width="36" customWidth="1"/>
            <col min="13" max="13" width="13" customWidth="1"/>
        </cols>
    <sheetData>
        <row r="1" spans="1:13" x14ac:dyDescent="0.25">
            <c r="A1" s="1" t="s"><v>0</v></c>
            <c r="B1" s="1" t="s"><v>1</v></c>
            <c r="C1" s="1" t="s"><v>2</v></c>
            ................................
            <c r="M13" s="3" t="s"><v>22</v></c>
        </row>
    </sheetData>
    <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
    <tableParts count="1"><tablePart r:id="rId1"/>
    </tableParts>

So table could be created either by parsing the associated sheet or in my case since I am creating the sheet in the first place I have the info I need to create the table xml files , and add them to the zip.

It may be possible to use pois XSSFTable class independently (it has a public constructor) and then render that to Xml, not sure.

这篇关于我可以使用 Apache-Poi 在流式模式下将 Excel 电子表格格式化为表格吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆