正如标题所示,以下是DTO:
public class PropertyQuery
{
public string UPRN { get; set; }
public DateTime? DateAdded { get; set; }
}
接着是OpenXML类,然后使用一种方法来创建电子表格并写入向下移动的字段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打算返回大约600多行。
任何建议都值得赞赏。谢谢。
答案 0 :(得分:0)
您是如此亲密。您遇到的问题是RowIndex
必须大于0,但您必须从0开始。
修复很简单;将count
的起始值从0
更改为1
。