【发布时间】:2012-08-06 16:22:57
【问题描述】:
string workbookPath = filePath;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(workbookPath, 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;
int rowCount = range.Rows.Count;
int columnCount = range.Columns.Count;
string[][] myArray = new string[rowCount][];
for (rCnt = 1; rCnt < rowCount; rCnt++)
{
myArray[rCnt] = new string[columnCount];
for (cCnt = 1; cCnt < columnCount; cCnt++)
{
object str = (range.Cells[rCnt, cCnt] as Excel.Range).get_Value();
-----> myArray[rCnt][cCnt] = str == null ? string.Empty : str.ToString();
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
return myArray;
以上是上传excel文件到sql数据库的代码。 本质上,当我传递 ----> 上面的 rCnt 和 cCnt 变量时……行数每次增加一次,列数增加两次……我希望列数增加到 3,或者有很多可用的列。
这样做的原因可能是在 excel csv 的第一行 - 单元格中没有任何内容 - 但是,在第 4-5 行中,第 3 列中有数据。
谁能看看我错过了什么?
任何问题/帮助将不胜感激。
【问题讨论】:
-
你应该在 0 开始
rCnt和cCnt -
感谢您的快速回复 - 这是我在上一行发生此类情况时收到的错误----> COMException is unhandled Exception from HRESULT: 0x800A03EC
-
对不起,我不明白:如果你都从 0 开始,你会得到这个异常吗?
-
是的,for (rCnt = 0 for (cCnt = 0
-
现在,在代码行:string StoreNumber = row[mapping[customer_no]["StoreNumber"]];我得到一个错误。它的工作方式是,从我指定的列号中找到商店编号:mapping["TRGT"]["StoreNumber"] = 0; 0 零是第 1 列。错误 - NullReferenceException 未处理:对象引用未设置为对象的实例