将excel中的列读取为c#
本文关键字:读取 excel | 更新日期: 2023-09-27 18:25:31
嗨,我正试图将excel文件读取到c#,但我想将列数据转换为字符串数组,然后再转换为字符串。我想我在这里已经做到了,但不确定。无论如何,当我试图为我的第二个if语句读取excel列的标题时,我得到了一个错误,说"索引超出了数组的界限。"。我是一个初学者,因此不明白我做错了什么。
if (xlApp != null)
{
//Doing excel things
int i = SheetNum;
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "'t", false, false, 0, true);
Excel.Sheets sheets = xlWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(i);
Excel.Range usedRange = worksheet.UsedRange;
Excel.Range colRange = usedRange.Columns;
Excel.Range firstRow = worksheet.UsedRange.Rows[1];
int rowCount = colRange.Rows.Count;
int colCount = colRange.Columns.Count;
for (int m = 1; m < colCount; m++)
{
for (int n = 0; n <= rowCount; n++)
{
System.Array myHeadvalues = (System.Array)firstRow.Cells.Value;
string[] HeaderData = myHeadvalues.OfType<object>().Select(o => o.ToString()).ToArray();
Excel.Range some = worksheet.UsedRange.Columns[m];
System.Array myNamevalues = (System.Array)some.Cells.Value;
string[] result1 = myNamevalues.OfType<object>().Select(o => o.ToString()).ToArray();
//String types
if (result1.Contains("Name") && HeaderData.Contains("Name"))
{
string tagval = HeaderData[n].ToString() + ".Array" +
string[] result = result1.Skip(1).ToArray();
string Inputs = result[n + 1].ToString();
System.Console.WriteLine(tagval, Inputs);
}
//Error Appears here//
else if (result1.Contains("Description") && HeaderData.Contains("Description"))
{
string tagval = HeaderData[n].ToString() + ".Array" +
string[] result = result1.Skip(1).ToArray();
string Inputs = result[n].ToString();
System.Console.WriteLine(tagval, Inputs);
}
}
}
}
Btw我修复了我的代码,现在它可以跨列读取,没有问题。如果有,我可以加快速度,请告诉我。谢谢
List<string> ColumnValues = new List<string>();
for (int n = 2; n < rowCount; n++)
{
for (int m = 1; m < colCount; m++)
{
Excel.Range some = worksheet.UsedRange.Columns[m];
System.Array myvalues = (System.Array)some.Cells.Value;
string[] Data = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
ColumnValues = Data.ToList();
System.Console.WriteLine(ColumnValues);
//String Types
if (ColumnValues.Contains("Name"))
{
string tagval = "Product_Array[0].Name";
string[] result = ColumnValues.Skip(1).ToArray();
}
}
}
}
它脱离了主题(我还不能发表评论),但它可能很有用:看起来你正在使用自动化或类似的东西。我建议使用像ClosedXML这样的库(这是免费的),因为它确实需要Excel应用程序来读取和写入Excel文件。在大多数情况下,库将比Excel应用程序更快地完成工作。