C#Excel Interop:无法从excel读取所有数据

时间:2012-05-16 08:54:16

标签: c# excel excel-interop

我在从xlsx文件中读取日期时遇到一些问题,我的意思是它没有读取单元格中的所有信息,例如我在单元格中有这个信息:

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

当我查看DataTable时,我只在行

中看到此信息
"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的单元格格式化为文本并且工作正常。我可以以编程方式将所有单元格格式更改为文本。 谢谢!

2 个答案:

答案 0 :(得分:3)

如果您希望将工作表中的所有单元格格式化为文本,则可以执行以下操作:

sheet.Cells.NumberFormat = "@";

答案 1 :(得分:1)

以下是使用C#访问Excel的框架。最好使用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);