如何在 C# 中正确设置 header 范围(使用 EPPlus)?
How to set correctly the header range in C# (use EPPlus)?
using System.IO;
using System.Collections.Generic;
using OfficeOpenXml;
namespace Project
{
public class CreateExcel
{
public static void GenerateExcel(List<string> headerList, List<string> dataList, FileInfo filePath)
{
using (ExcelPackage excel = new ExcelPackage())
{
excel.Workbook.Worksheets.Add("Worksheet1");
// Determine the header range (e.g. A1:D1)
string headerRange = "A1:" + Char.ConvertFromUtf32(headerList.Count + 64) + "1";
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
// Popular header row data
worksheet.Cells[headerRange].LoadFromCollection(headerList);
worksheet.Cells[2, 1].LoadFromCollection(dataList, false);
excel.SaveAs(filePath);
}
}
}
我想用这个函数创建 .xlsx 文件,但是 headerRange 得到“A1:^1”值(当我使用我的 headerList 时,它有 30 个元素),当然我得到这个错误:System.Exception: 'Invalid Address format ^1'
.
如何正确设置headerRange?
改用LoadFromArrays
:
var values=new List<object[]> {
headerList.ToArray(),
dataList.ToArray()
};
worksheet.Cells["A1"].LoadFromArrays(values);
LoadFromCollection
使用反射从强类型集合中加载数据,为每个 属性
创建不同的列
using System.IO;
using System.Collections.Generic;
using OfficeOpenXml;
namespace Project
{
public class CreateExcel
{
public static void GenerateExcel(List<string> headerList, List<string> dataList, FileInfo filePath)
{
using (ExcelPackage excel = new ExcelPackage())
{
excel.Workbook.Worksheets.Add("Worksheet1");
// Determine the header range (e.g. A1:D1)
string headerRange = "A1:" + Char.ConvertFromUtf32(headerList.Count + 64) + "1";
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
// Popular header row data
worksheet.Cells[headerRange].LoadFromCollection(headerList);
worksheet.Cells[2, 1].LoadFromCollection(dataList, false);
excel.SaveAs(filePath);
}
}
}
我想用这个函数创建 .xlsx 文件,但是 headerRange 得到“A1:^1”值(当我使用我的 headerList 时,它有 30 个元素),当然我得到这个错误:System.Exception: 'Invalid Address format ^1' . 如何正确设置headerRange?
改用LoadFromArrays
:
var values=new List<object[]> {
headerList.ToArray(),
dataList.ToArray()
};
worksheet.Cells["A1"].LoadFromArrays(values);
LoadFromCollection
使用反射从强类型集合中加载数据,为每个 属性