C# C如何使用互操作从多页excel中读取指定的单元格?
我需要在excel文件的第一页和第二页中读取B2到H10 5行7列。我下面的代码用于从两个工作表中读取每个单元格,如何从两个工作表中读取我需要的单元格?我看到了很多使用activeworksheet的解决方案,但没有指定它正在读取的工作表,这无法解决我的问题C# C如何使用互操作从多页excel中读取指定的单元格?,c#,excel,excel-interop,C#,Excel,Excel Interop,我需要在excel文件的第一页和第二页中读取B2到H10 5行7列。我下面的代码用于从两个工作表中读取每个单元格,如何从两个工作表中读取我需要的单元格?我看到了很多使用activeworksheet的解决方案,但没有指定它正在读取的工作表,这无法解决我的问题 using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; Excel.Appli
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);
}
}
我们应该这样做
更多示例可在中找到。我找到了解决方案,下面更新了我的代码
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);
}
}
感谢您的回答,但它给出了一个异常Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“无法将类型“bool”隐式转换为“Microsoft.Office.Interop.Excel.Range”
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);
}
}