从c#中的excel读取列索引和列值

时间:2013-11-07 05:35:28

标签: c# .net excel

我有一个c#应用程序,它从excel文件中读取数据。

我用过

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

这是从A1到B6单元读取值

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

键值

A1 Value1

B1 Value2

A2 Value3

B2 Value4

2 个答案:

答案 0 :(得分: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;

我希望这会有所帮助

答案 1 :(得分: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....!
            }
        }
    }

}