gpt4 book ai didi

c# - 使用 C# 从组合的 Excel 列/行中读取数据

转载 作者:太空狗 更新时间:2023-10-29 21:46:20 27 4
gpt4 key购买 nike

我正在尝试使用 Microsofts COM Interop 从 C# 中的 Excel 文档中读取数据。

到目前为止,我能够加载文档并从中读取一些数据。但是,我需要从两个不同的列读取数据并将它们输出为 json(用于 jquery ajax 调用)

我对我的 Excel 文档的结构做了一个快速原型(prototype),希望它更容易解释 ;-)

enter image description here

我使用的方法称为 GetExcelDataByCategory(string categoryName),其中 categoryName 参数将用于查找从哪一列获取数据。

因此,也就是说,如果我使用“类别 2”作为参数进行调用,我需要获取 C 列行中的所有值 A 列中的相应日期,所以输出将如下所示:

enter image description here

然后需要将其转换/解析为 JSON。

我搜索了很多关于如何实现这一点的方法,但到目前为止没有运气 :-( 我知道我可以使用 get_Range() 方法来选择一个范围,但你似乎需要明确地告诉方法从哪一行和哪一列获取数据。即:get_Range("A1, C1")

这是我第一次从 Excel 文档中读取数据,所以我想还有很多东西要学;-) 有没有办法在我的第二张图片上获取输出?

非常感谢任何帮助/提示! :-)

提前致谢。

祝一切顺利

最佳答案

这是我会做的:

using Excel = Microsoft.Office.Interop.Excel;

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("path to book");
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange; // get the entire used range

int numberOfRows = xlRange.Rows.Count;
int numberOfCols = xlRange.Columns.Count;
List<int> columnsToRead = new List<int>();
// find the columns that correspond with the string columnName which
// would be passed into your method
for(int i=1; i<=numberOfCols; i++)
{
if(xlRange.Cells[1,i].Value2 != null) // ADDED IN EDIT
{
if(xlRange.Cells[1,i].Value2.ToString().Equals(categoryName))
{
columnsToRead.Add(i);
}
}
}
List<string> columnValue = new List<string>();
// loop over each column number and add results to the list
foreach(int c in columnsToRead)
{
// start at 2 because the first row is 1 and the header row
for(int r = 2; r <= numberOfRows; r++)
{
if(xlRange.Cells[r,c].Value2 != null) // ADDED IN EDIT
{
columnValue.Add(xlRange.Cells[r,c].Value2.ToString());
}
}
}

这是我用来读取 Excel 的代码。现在,它读取具有标题(由第一行中的任何内容指定)的每一列,然后读取那里的所有行。这并不完全符合您的要求(它没有格式化为 JSON),但我认为这足以让您渡过难关。


编辑:看起来有一些空白单元格导致了问题。 Interop 中的空白单元格将为 NULL,因此如果我们尝试调用 Value2 或 Value2.ToString() 会出错,因为它们不存在。我添加了代码来检查以确保在对单元格进行任何操作之前该单元格不为空。它可以防止错误。

关于c# - 使用 C# 从组合的 Excel 列/行中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9703539/

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