OpenXML编写器列

时间:2013-05-31 01:51:28

标签: c# excel openxml

我有一个问题要问使用OpenXMLWriter。

我目前正在使用下面的代码创建我的excel文件,但我想设置列的宽度。我该怎么办?

因为我试图在Worksheet()和SheetData()之间编写新的Columns,到目前为止我没有成功。

示例非常有用。感谢它,谢谢!

using (SpreadsheetDocument xl = SpreadsheetDocument.Create("LargeFile.xlsx", SpreadsheetDocumentType.Workbook))
{
    List<OpenXmlAttribute> oxa;
    OpenXmlWriter oxw;

    xl.AddWorkbookPart();
    WorksheetPart wsp = xl.WorkbookPart.AddNewPart<WorksheetPart>();

    oxw = OpenXmlWriter.Create(wsp);
    oxw.WriteStartElement(new Worksheet());
    oxw.WriteStartElement(new SheetData());

    for (int i = 1; i <= 50000; ++i)
    {
        oxa = new List<OpenXmlAttribute>();
        // this is the row index
        oxa.Add(new OpenXmlAttribute("r", null, i.ToString()));

        oxw.WriteStartElement(new Row(), oxa);

        for (int j = 1; j <= 100; ++j)
        {
            oxa = new List<OpenXmlAttribute>();
            // this is the data type ("t"), with CellValues.String ("str")
            oxa.Add(new OpenXmlAttribute("t", null, "str"));

            // it's suggested you also have the cell reference, but
            // you'll have to calculate the correct cell reference yourself.
            // Here's an example:
            //oxa.Add(new OpenXmlAttribute("r", null, "A1"));

            oxw.WriteStartElement(new Cell(), oxa);

            oxw.WriteElement(new CellValue(string.Format("R{0}C{1}", i, j)));

            // this is for Cell
            oxw.WriteEndElement();
        }

        // this is for Row
        oxw.WriteEndElement();
    }

2 个答案:

答案 0 :(得分:7)

在这些代码行之间:

oxw.WriteStartElement(new Worksheet());
oxw.WriteStartElement(new SheetData());

添加额外的代码部分:

oxw.WriteStartElement(new Worksheet());

oxw.WriteStartElement(new Columns());

oxa = new List<OpenXmlAttribute>();
// min and max are required attributes
// This means from columns 2 to 4, both inclusive
oxa.Add(new OpenXmlAttribute("min", null, "2"));
oxa.Add(new OpenXmlAttribute("max", null, "4"));
oxa.Add(new OpenXmlAttribute("width", null, "25"));
oxw.WriteStartElement(new Column(), oxa);
oxw.WriteEndElement();

oxa = new List<OpenXmlAttribute>();
oxa.Add(new OpenXmlAttribute("min", null, "6"));
oxa.Add(new OpenXmlAttribute("max", null, "6"));
oxa.Add(new OpenXmlAttribute("width", null, "40"));
oxw.WriteStartElement(new Column(), oxa);
oxw.WriteEndElement();

oxw.WriteEndElement();

oxw.WriteStartElement(new SheetData());

答案 1 :(得分:0)

简单的方法是使用Excel模板并根据需要更改宽度。 稍后当您写入数据时,列宽将自动保留。

另一种方式是: 使用OpenXML生产力工具反映所需excel文件的代码。然后使用文件中的样式信息以编程方式设置单元格/列宽。