C#如何使用interop从多张表格中读取指定的单元格?

时间:2018-06-08 02:24:12

标签: c# excel excel-interop

我需要阅读" B2"到" H10" (第5行,第7列)第一张工作表和第二张excel文件。我的下面的代码用于从两张纸上读取每个单元格,如何从两张纸上读取我需​​要的单元格? (我看到很多使用activeworksheet的解决方案,但没有指定哪个表格无法解决我的问题。)

        using Excel = Microsoft.Office.Interop.Excel;
        using System.Runtime.InteropServices;

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        string str;
        int rCnt;
        int cCnt;
        int rw = 0;
        int cl = 0;

        xlApp = new Excel.Application();

        xlWorkBook = xlApp.Workbooks.Open("PATH", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("sheetName");
        range = xlWorkSheet.UsedRange;

        rw = range.Rows.Count;
        cl = range.Columns.Count;


        for (rCnt = 1; rCnt <= rw; rCnt++)
        {

            for (cCnt = 1; cCnt <= cl; cCnt++)
            {

                str = ((range.Cells[rCnt, cCnt] as Excel.Range).Value2).ToString();
                MessageBox.Show(str);

            }

        }

2 个答案:

答案 0 :(得分:1)

我找到了解决方案,我的代码在下面更新。

    using Excel = Microsoft.Office.Interop.Excel;
    using System.Runtime.InteropServices;

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    Excel.Range range, sRange;

    string str;
    int rCnt;
    int cCnt;
    int rw = 0;
    int cl = 0;

    xlApp = new Excel.Application();

    xlWorkBook = xlApp.Workbooks.Open("PATH", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("sheetName");
    range = xlWorkSheet.Cells;
    sRange = range.Range["B2", "H10"];
    rw = sRange.Rows.Count;
    cl = sRange.Columns.Count;


    for (rCnt = 1; rCnt <= rw; rCnt++)
    {

        for (cCnt = 1; cCnt <= cl; cCnt++)
        {

            str = ((sRange.Cells[rCnt, cCnt] as Excel.Range).Value2).ToString();
            MessageBox.Show(str);

        }

    }

答案 1 :(得分:0)

foreach(var row in tableRows)  {
 var processedValue = ProcessColumn(row.columnToBeProcessed)  
 InsertIntoResultTable(row.column1, row.column2, processedValue
}

应该做的伎俩

更多示例可在https://www.add-in-express.com/creating-addins-blog/2013/10/15/excel-cell-values-formulas-formatting-csharp/

找到