1

我有从 excel 文件中读取数据的 ac# 应用程序。

我用了

Range xlRng = (Range)workSheet.get_Range("A1:B6", Missing.Value);

这是从 A1 到 B6 单元格读取值

如果我给了一个范围,我需要读取字典的值,键名必须是单元格索引,值必须是相应的单元格值

核心价值

A1 值1

B1 价值 2

A2 值3

B2 价值4

4

2 回答 2

3

你也可以试试这个

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;

我希望这会有所帮助

于 2013-11-07T06:48:01.837 回答
1

你试过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....!
            }
        }
    }

}
于 2013-11-07T06:31:52.883 回答