gpt4 book ai didi

c# - 将excel中的列读取到c#

转载 作者:行者123 更新时间:2023-12-04 20:12:46 24 4
gpt4 key购买 nike

您好我正在尝试将 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);

}
}
}
}

最佳答案

顺便说一句,我现在修复了我的代码,它可以毫无问题地跨列读取。如果有无论如何我可以加快速度,请告诉我。谢谢。

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();

}


}


}

}

关于c# - 将excel中的列读取到c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com