0

ExcelでExcelファイルを読み取ろうとしていますが、何らかの理由で最初の列が欠落し、最初の行がデータから欠落しています。

ファイルをExcelで開き、変更せずに保存すると、ファイルが正しく読み取られます。

これがどのように起こるかについてのアイデアはありますか?

以下は、ファイルを読み取るために使用しているコードです。

string xlConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
            + "Data Source="
            + txt_InputFile.Text
            + ";Extended Properties=Excel 8.0;";

using (OleDbConnection dbConnection = new OleDbConnection(xlConn))
{
    dbConnection.Open();

    // Get the name of the first worksheet:
    DataTable dbSchema = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    if (dbSchema == null || dbSchema.Rows.Count < 1)
    {
        //"Error: Could not determine the name of the first worksheet."
        throw new Exception(Program.lm_GetMethodLanguage(this.GetType().Name, "wp_InputFile_CloseFromNext", 5) );
    }
    string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();

    using (
        OleDbDataAdapter dbCommand = new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]",
                                                            dbConnection))
    {
        using (DataSet myDataSet = new DataSet())
        {
            dbCommand.Fill(myDataSet);

            inputData = myDataSet.Tables[0];
        }
    }
}
4

1 に答える 1

-1

これを使用します。これにより、Excel シートのすべてのシートが取得されます。

    private String[] GetExcelSheetNames(string excelFile)
    {
        try
        {
            excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ""yoursourcepath"+ ";Extended Properties=Excel 12.0;Persist Security Info=False";
            excelConnection = new OleDbConnection(excelConnectionString);
            excelConnection.Open();
            dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            if (dt == null)
            {
                return null;
            }

            excelSheets = new String[dt.Rows.Count];
            int i = 0;


            foreach (DataRow row in dt.Rows)
            {
                excelSheets[i] = row["TABLE_NAME"].ToString();
                i++;
            }

            return excelSheets;
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            if (excelConnection != null)
            {
                excelConnection.Close();
                excelConnection.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }
    }
于 2013-03-11T15:05:53.830 に答える