在C#中将所有列作为字符串读取Excel

时间:2013-03-27 20:12:09

标签: c# string excel type-conversion

我试图在Excel中将Excel列作为字符串读取。我写了以下代码:

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

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

3 个答案:

答案 0 :(得分:1)

在codeproject上查看this。如评论中所述,如果您使用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();
    }
}

答案 1 :(得分:0)

嗯。不知道它是否有帮助,但我遇到了同样的问题。现在它适用于我,使用以下连接字符串:

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

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

答案 2 :(得分: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;
        }