在C#中将所有列读取为string

我正在尝试在C#中读取Excel列作为string。 我写了下面的代码:

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:\\pack.xls;" + "Extended Properties=\"Excel 8.0;IMEX=1\""; 

问题是,在一列中,我有混合的数据types,如数字,string。 我已经在寻找解决scheme,但没有一个对我有帮助。 下面的链接没有帮助我( https://stackoverflow.com/questions/11200472/read-excel-columns-as-text我发现,Excel决定哪种types将根据前10栏列。如何修复这个问题?我正在使用Microsoft.Office.Interop.Excel。

看看这个代码项目。 如注释中所述,如果您使用Interop,则不需要连接string。 你可以简单地打开一个工作簿,获取一个数组(一个对象数组),并在每个项目上调用ToString()来获得它的string表示。 像这样的东西应该这样做:

 ApplicationClass app = new ApplicationClass(); app.Visible = false; app.ScreenUpdating = false; app.DisplayAlerts = false; Workbook book = app.Workbooks.Open(@"path\Book1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); Worksheet sheet = (Worksheet)book.Worksheets[1]; Range range = sheet.get_Range(...); string execPath = Path.GetDirectoryName( Assembly.GetExecutingAssembly().CodeBase); object[,] values = (object[,])range.Value2; for (int i = 1; i <= values.GetLength(0); i++) { for (int j = 1; j <= values.GetLength(1); j++) { string s = values[i, j].ToString(); } } 

嗯。 不知道是否有帮助,但我有同样的问题。 现在它适用于我以下连接string:

 <add name="Excel2010File" connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=&quot;Excel 12.0;READONLY=TRUE;IMEX=1&quot;" providerName="Microsoft.ACE.OLEDB.12.0" /> 

如果没有,可以在网上find我的提供商的库(对不起,没有链接)。 即使使用较低版本的Excel文件,也可以将其设置为12.0

我通常做的是:

  Range FirstCell = YourWorkSheet.Range["A1"]; //Use the Header of the column you want instead of "A1", or even a name you give to the cell in the worksheet. List<string> ColumnValues = new List<string>(); int i = 1; object CellValue = FirstCell.Offset[i, 0].Value; while (CellValue != null) { ColumnValues.Add(CellValue.ToString()); i++; CellValue = FirstCell.Offset[i,0].Value; }