在OpenXML(excel)

时间:2015-12-19 19:57:25

标签: c# excel openxml openxml-sdk

我是OpenXML的新手(2.5版),我可以创建行和单元格,但我需要能够设置列宽,但由于某些原因我无法正确执行。

没有此代码:

        Columns cols = new Columns();

        Column c1 = new Column()
        {
            CustomWidth = true,
            Width = 20
        };

        cols.Append(c1);
        wspart.Worksheet.Append(cols);

程序运行并生成excel文件。

下面的代码符合并运行,但留下了一个损坏的Excel文档。当我尝试添加列时,我做错了什么?

    public static void createExcel() //TODO change to private
    {
        //create the spreadsheet document with openxml See https://msdn.microsoft.com/en-us/library/office/ff478153.aspx
        SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Create(@"C:\Users\Reid\Documents\BLA\test.xlsx", SpreadsheetDocumentType.Workbook); //TODO change path

        //add a workbook part
        WorkbookPart wbpart = spreadsheetDoc.AddWorkbookPart();
        wbpart.Workbook = new Workbook();

        //add a worksheet part
        WorksheetPart wspart = wbpart.AddNewPart<WorksheetPart>();
        Worksheet ws = new Worksheet(new SheetData());
        wspart.Worksheet = ws;

        //create a new sheets array
        Sheets sheets = spreadsheetDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

        //create a new sheet
        Sheet sheet = new Sheet()
        {
            Id = spreadsheetDoc.WorkbookPart.GetIdOfPart(wspart),
            SheetId = 1,
            Name = "mySheet" //TODO change name
        };

        //add the sheet to the workbook sheet aray
        sheets.Append(sheet);

        SheetData shData = wspart.Worksheet.GetFirstChild<SheetData>();

        //////////////////////////////////row and col widths//////////////////////
        Columns cols = new Columns();

        Column c1 = new Column()
        {
            CustomWidth = true,
            Width = 20
        };

        cols.Append(c1);
        wspart.Worksheet.Append(cols);

        //create the first row
        Row r1 = new Row
        {
            RowIndex = 1,
            CustomHeight = true,
            Height = 71.25 //change height based on info
        };
        shData.Append(r1);
  ////////////////////////cell data/////////////////////////////////

        // In the new row, find the column location to insert a cell in A1.
        Cell refCell = null;
        foreach (Cell cell in r1.Elements<Cell>())
        {
            if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
            {
                refCell = cell;
                break;
            }
        }
        // Add the cell to the cell table at A1.
        Cell newCell = new Cell() {
            CellReference = "A1",
        };
        r1.InsertBefore(newCell, refCell);

        // Set the cell value to be a numeric value of 100.
        newCell.CellValue = new CellValue("100");


        //TODO add in standard things (text that is always the same, headers, logos, etc.)

        //TODO add in dynamic text

        //TODO create and add in barcodes

        //Save and close the document
        wbpart.Workbook.Save();
        spreadsheetDoc.Close();

        //TODO send document to database
    }

2 个答案:

答案 0 :(得分:15)

上面选择的答案并没有解决我的问题,但我终于明白了。对我来说问题是当我调用该行时:Columns columns1=worksheet1.GetFirstChild<Columns>();工作表中当前没有Columns个子项,因此返回的对象为null,当我尝试向{00添加列时出现运行时错误{1}}对象。

问题是Excel非常挑剔。实际sheet.xml文件中的columns元素必须位于sheetdata元素之前。尝试将我的自定义列附加到工作表导致文件损坏,因为它将columns元素放在了sheetdata元素之后。因为我知道它必须在sheetdata元素之前,我必须将它插入到工作表的开头而不是将其附加到工作表。以下代码对我有用:

Columns

希望这有助于某人!!

答案 1 :(得分:1)

我遇到了同样的问题,即 .GetFirstChild<Columns> 为空。创建 Columns 对象并在索引 0 处插入(与其他答案一样)使 Excel 抱怨该文件无效。相反,它似乎需要在 SheetData 部分之前的列定义:

if (needToInsertColumns)
{
    var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
    worksheetPart.Worksheet.InsertBefore(columnsList, sheetData);
}