使用 EPPlus 迭代并将所有列名添加到 ComboBox
Iterating and adding all column names to a ComboBox using EPPlus
我需要将 sheet 中的列名称添加到组合框
我试过以下
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
var ws = pck.Workbook.Worksheets[1];
int totalCols = ws.Dimension.End.Column;
for (int i = 1; i <= totalCols; i++)
{
comboBox1.Items.Add( (ws.Column(i).ToString()));
}
}
但这会产生空引用异常。
为什么会这样?
确保您正确加载包并正确选择值:
// Select workbook
var fileInfo = new FileInfo(@"yourfile.xlsx");
// Load workbook
using (var package = new ExcelPackage(fileInfo)) {
// Itterate through workbook sheets
foreach (var sheet in package.Workbook.Worksheets){
// Itterate through each column until final column
for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
comboBox1.Items.Add(sheet.Cells[1, i].Text);
}
}
}
这在新工作簿中正确运行,每个 sheet 的列中有两个 sheet 和值。
我需要将 sheet 中的列名称添加到组合框
我试过以下
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
var ws = pck.Workbook.Worksheets[1];
int totalCols = ws.Dimension.End.Column;
for (int i = 1; i <= totalCols; i++)
{
comboBox1.Items.Add( (ws.Column(i).ToString()));
}
}
但这会产生空引用异常。
为什么会这样?
确保您正确加载包并正确选择值:
// Select workbook
var fileInfo = new FileInfo(@"yourfile.xlsx");
// Load workbook
using (var package = new ExcelPackage(fileInfo)) {
// Itterate through workbook sheets
foreach (var sheet in package.Workbook.Worksheets){
// Itterate through each column until final column
for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
comboBox1.Items.Add(sheet.Cells[1, i].Text);
}
}
}
这在新工作簿中正确运行,每个 sheet 的列中有两个 sheet 和值。