【问题标题】:Read column index and column value from an excel in c#从 C# 中的 excel 中读取列索引和列值
【发布时间】: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

【问题讨论】:

    标签: c# .net excel


    【解决方案1】:

    你也可以试试这个

    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;
    

    我希望这会有所帮助

    【讨论】:

    • 谢谢你.. string cellValue = cell.Value;将此修改为字符串 cellValue = cell.Value2;所以请编辑你的答案,谢谢你
    • 请修改您的答案
    • 哦,很抱歉迟到了,cell.Value 对我有用。无论如何,我已经根据您的建议更改了答案。谢谢。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多