【发布时间】:2013-11-07 05:35:27
【问题描述】:
我有一个从 excel 文件中读取数据的 c# 应用程序。
我用过
Range xlRng = (Range)workSheet.get_Range("A1:B6", Missing.Value);
从 A1 到 B6 单元格读取值
如果我给了一个范围,我需要将值读取到字典中,键名必须是单元格索引,值必须是对应的单元格值
关键价值
A1 值1
B1 值2
A2 值3
B2 价值 4
【问题讨论】:
我有一个从 excel 文件中读取数据的 c# 应用程序。
我用过
Range xlRng = (Range)workSheet.get_Range("A1:B6", Missing.Value);
从 A1 到 B6 单元格读取值
如果我给了一个范围,我需要将值读取到字典中,键名必须是单元格索引,值必须是对应的单元格值
关键价值
A1 值1
B1 值2
A2 值3
B2 价值 4
【问题讨论】:
你也可以试试这个
Excel.Range xlRng = (Excel.Range)workSheet.get_Range("A1:B6", Type.Missing);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (Excel.Range cell in xlRng)
{
string cellIndex = cell.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
string cellValue = Convert.ToString(cell.Value2);
dic.Add(cellIndex, cellValue);
}
如果你和我一样使用 Excel 命名空间,别忘了导入命名空间
using Excel = Microsoft.Office.Interop.Excel;
我希望这会有所帮助
【讨论】:
你试过EPPlus吗?
这里是可以做你想做的示例代码:
void Main()
{
var existingFile = new FileInfo(@"c:\temp\book1.xlsx");
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile))
{
// Get the work book in the file
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
// Get the first worksheet
ExcelWorksheet sheet = workBook.Worksheets.First();
// read some data
Dictionary<string,double> cells = (from cell in sheet.Cells["A1:B6"]
where cell.Start.Column == 1
select sheet.Cells[cell.Start.Row,cell.Start.Column,cell.Start.Row,2].Value)
.Cast<object[,]>()
.ToDictionary (k => k[0,0] as string, v => (double)(v[0,1]));
//do what you need to do with the dictionary here....!
}
}
}
}
【讨论】: