在c#中读取Excel的所有列作为字符串

本文关键字:字符串 读取 Excel | 更新日期: 2023-09-27 18:06:15

我试图在c#中读取Excel列作为字符串。我写了下面的代码:

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

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

在c#中读取Excel的所有列作为字符串

看看这个代码项目。正如评论中所述,如果您正在使用Interop,则不需要连接字符串。您可以简单地打开工作簿,获取项目数组(对象数组)并对每个项目调用ToString()以获得其字符串表示形式。像这样的代码应该做:

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();
    }
}

我通常是这样做的:

        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;
        }

嗯。不知道这是否有帮助,但我也有同样的问题。现在它为我工作与以下连接字符串:

<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" />

你可以在网上找到我的供应商的库(抱歉,没有链接了),如果你没有它。您可以将其设置为12.0,即使是较低版本的excel文件。