我正在从Excel工作表中检索信息, 我想从excel表中获取信息并将其插入一个2个dementional数组中,以便我以后可以使用它。 它总是从行[1,1]开始填充而忽略其余部分。任何想法我怎么能从[0,0]开始。这是我正在使用的代码。
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
var strs = openFileDialog1.InitialDirectory;
var name = openFileDialog1.FileName;
var path = strs + name;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str = "";
int rCnt = 0;
int cCnt = 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(1);
range = xlWorkSheet.UsedRange;
Hashtable myHT = new Hashtable();
int countRow = 0;
string[,] myArray;
myArray = new string[range.Rows.Count, range.Columns.Count];
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
//str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
myArray[cCnt, rCnt] = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
//MessageBox.Show(str);
}
countRow++;
}
label1.Text = Convert.ToString(countRow);
xlWorkBook.Close(true, null, null);
xlApp.Quit();
答案 0 :(得分:0)
UsedRange
属性显然非常古怪,并不总是返回正确的范围。这是一个替代方案的链接:
答案 1 :(得分:0)
只需更改行:
myArray[cCnt, rCnt] = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
为:
myArray[cCnt - 1, rCnt - 1] = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
答案 2 :(得分:0)
在我看来,您只需要将索引偏移到电子表格中:
for (int row = 0; row < range.Rows.Count; row++)
{
for (int column; column < range.Columns.Count; column++)
{
// Offset indexing into range.Cells as Excel is 1-based
Excel.Range range = (Excel.Range) range.Cells[row + 1, column + 1];
myArray[column, row] = (string) range.Value2;
}
}
(我已经删除了countRow
位,因为您可以从range.Rows.Count
获取该位。我还重命名了变量以便清晰,并稍微重构了循环体。)