从 DTO 在 C# 中使用 OpenXML 写入单元格

Writing to cells using OpenXML in C# from DTO

正如标题所示,下面是 DTO:

public class PropertyQuery
{
    public string UPRN { get; set; }

    public DateTime? DateAdded { get; set; }
}

随后是 OpenXML class,其方法应该是创建电子表格并写入字段 A 和 B,向下移动:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public class OpenXML
{

    public static void BuildWorkbook(string filename, List<PropertyQuery> query)
    {
        using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
        {
            WorkbookPart wbp = xl.AddWorkbookPart();
            WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
            Workbook wb = new Workbook();
            FileVersion fv = new FileVersion();
            fv.ApplicationName = "Microsoft Office Excel";

            Worksheet ws = new Worksheet();
            SheetData sd = new SheetData();

            Row r1 = new Row();
            Row r2 = new Row();
            Cell c1 = new Cell();
            Cell c2 = new Cell();

            uint count = 0;

            foreach (var i in query)
            {
                r1 = new Row();
                r2 = new Row();
                c1 = new Cell();
                c2 = new Cell();

                string UPRN = i.UPRN.ToString();
                string dateAdded = i.DateAdded.ToString();

                r1.RowIndex = count;
                r2.RowIndex = count;

                c1.CellReference = "A" + r1.RowIndex;
                c2.CellReference = "B" + r2.RowIndex;

                c1.DataType = CellValues.String;
                c2.DataType = CellValues.String;

                c1.CellValue = new CellValue(UPRN);
                c2.CellValue = new CellValue(dateAdded);

                r1.Append(c1);
                r2.Append(c2);

                sd.Append(r1);
                sd.Append(r2);

                count++;
            }

            ws.Append(sd);
            wsp.Worksheet = ws;

            wsp.Worksheet.Save();
            Sheets sheets = new Sheets();
            Sheet sheet = new Sheet();
            sheet.Name = "Data";
            sheet.SheetId = 1;
            sheet.Id = wbp.GetIdOfPart(wsp);
            sheets.Append(sheet);
            wb.Append(fv);
            wb.Append(sheets);

            xl.WorkbookPart.Workbook = wb;
            xl.WorkbookPart.Workbook.Save();
            xl.Close();
        }
    }
}

我的代码运行并创建了电子表格,但是当我尝试打开它时,系统通知我它已损坏。 DTO 意味着 return 大约 600 多行。

如有任何建议,我们将不胜感激。谢谢。

你太接近了。您遇到的问题是 RowIndex 必须大于 0,但您的从 0 开始。

修复很简单;将 count 的起始值从 0 更改为 1.