从Excel读取会留下空白单元格C#

时间:2019-02-21 15:32:56

标签: c# excel datatable

我必须编写一个程序,该程序将从Excel文件读取并将其放入DataTable中,以导出到具有更改的列标题的另一个Excel文件。列中的数据应保持不变。我目前可以将其保存到DataTable中,但是我丢失了大量信息(单个单元格为空/空)。

这是我的Excel文件的外观:

+----------------------------------------------+
|  ID   |  AccNum  | CustName  | City  | State | 
+----------------------------------------------+
| 02345 |  065812  | CustName1 | City1 |  KS   |
| 02346 |  087425  | CustName2 | City2 |  MO   |
| 02347 |  054785  | CustName3 | City3 |  KS   |
| ..... |  ......  | ......... | ..... |  ..   |
+----------------------------------------------+

到目前为止,用于将Excel读取到DataTable的代码:

public DataTable ReadExcel(string fileName, string TableName)
{
    //Creates new DataTable for results
    DataTable table = new DataTable();
    //Creates connection string for Excel file
    OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
    //Creates command to be ran
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + TableName + "$]", connection);

    try
    {
        //Launches connection
        connection.Open();
        //Creates and Executes data reader
        OleDbDataReader reader = cmd.ExecuteReader();
        //Loop until the reader closes
        while (!reader.IsClosed)
        {
            //Load reader data to DataTable
            table.Load(reader);
        }
    }
    catch (OleDbException ode)
    {
        Console.WriteLine("ERROR: " + ode.Message);
    }
    finally
    {
        //No matter what- close the connection
        connection.Close();
    }


    //Return the DataTable
    return table;
}

我的预期输出是匹配示例Excel文件格式。但是,我得到以下信息:

+----------------------------------------------+
|  ID   |  AccNum  | CustName  | City  | State | 
+----------------------------------------------+
|  2345 |   65812  | CustName1 | City1 |  KS   |
|       |   87425  | CustName2 | City2 |  MO   |
|  2347 |   54785  | CustName3 | City3 |  KS   |
| ..... |  ......  | ......... | ..... |  ..   |
+----------------------------------------------+

唯一丢失的数据是ID数字以及要保留的一些前导零。对于本示例数据,出于篇幅的考虑,我仅提供了三个customer示例。数据越多,丢失的ID数字就越多,但顺序没有特定。

我不正确地获取数据吗?有什么我想念的吗?我很乐意回答任何问题。预先感谢。

0 个答案:

没有答案