2012-05-16 58 views
0

從xlsx文件讀取日期時出現了一些問題,我的意思是它沒有讀取單元格中的所有信息,例如我有在單元格這樣的信息:C#Excel Interop:無法讀取excel中的所有數據

"4876112","3456151712","345627712","3125HPC21017500011","34131HPC210349014112","35134HPC210273008212" 

,當我檢查,看看數據表,我只看到了這行信息

"4876112","3456151712","345627712", 

這是我的代碼:

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); 
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(input, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); 

string sheetname = ""; 

foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in workbook.Sheets) 
{ 
    sheetname = sheet.Name; 
    break; 
} 

string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", input); 
string query = String.Format("select * from [{0}$]", sheetname); 
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString); 
DataSet ds = new DataSet(); 
dataAdapter.Fill(ds); 
tabela = ds.Tables[0]; 

我輸入並將Excel的單元格形成文本並正常工作。我可以編程方式將所有單元格格式更改爲文本。 謝謝!

+0

爲什麼你使用OleDB讀取excel數據,當你已經使用Interop for Excel?您可以從「工作表」中讀取數據。 – TcKs

+0

注意:'sheetname = workbook.Sheets [0] .Name'會更簡單(而不是'foreach'和'break')嗎? – Filburt

回答

3

如果你想在工作表中的所有單元格格式化爲文本,你可以簡單地做:

sheet.Cells.NumberFormat = "@"; 
+0

我用這個代碼行,但它要求我保存文檔。 – XandrUu

+0

這是因爲這會修改文檔。你在使用它後關閉xls嗎?如果是這種情況,你可以在不保存的情況下關閉它:workbook.Close(false,System.Reflection.Missing.Value,System.Reflection.Missing.Value); –

1

這裏有一個如何Excel可以使用C#進行訪問的骨架。使用C#4.0或更新版本會更好,因爲它具有更好的COM互操作性。

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

... 
//create objects 
Excel.Application oXL; 
Excel._Workbook oWB; 
Excel._Worksheet oSheet; 

oXL   = new Excel.Application(); 
oXL.Visible = false; 
oWB   = oXL.Workbooks.Open(template_file); 
oSheet  = (Excel._Worksheet)oWB.Worksheets[1]; 

//set cell values 
oSheet.Cells[1, 1] = "my value here"; 

//set formatting 
oSheet.get_Range("A1", "A15").Font.Bold   = true; 
oSheet.get_Range("A1", "A15").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; 
oSheet.get_Range("A1", "A15").ColumnWidth  = 20; 

//close 
oXL.ActiveWorkbook.Close(); 
Marshal.ReleaseComObject(oWB); 
Marshal.ReleaseComObject(oSheet); 
Marshal.ReleaseComObject(oXL);