简体   繁体   中英

reading excel (.xlsx) file in c#

I am reading .xlsx file using c# like this

string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
                             ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";

var output = new DataSet();

using (var conn = new OleDbConnection(strConn))
{
    conn.Open();

    var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

    foreach (DataRow row in dt.Rows)
    {
        string sheet = row["TABLE_NAME"].ToString();

        var cmd = new OleDbCommand("SELECT * FROM [+"+sheet+"+]", conn);
        cmd.CommandType = CommandType.Text;

        OleDbDataAdapter xlAdapter = new OleDbDataAdapter(cmd);

        xlAdapter.Fill(output,"School");
    }
}

But I am getting error at xlAdapter.Fill(output,"School"); Error is

The Microsoft Office Access database engine could not find the object '+_xlnm.Print_Area+'.  Make sure the object exists and that you spell its name and the path name correctly.

I am not able to figure out that what is wrong happening in code.

I believe your sheet is named _xlnm.Print_Area . Try changing this line

var cmd = new OleDbCommand("SELECT * FROM [+"+sheet+"+]", conn);

to

var cmd = new OleDbCommand("SELECT * FROM ["+sheet+"]", conn);

variable sheet contains value: +_xlnm.Print_Area+

This +_xlnm.Print_Area+ does not actually exists.

Thats why error is comming.

Check with that object.

I would check what you are getting in row["TABLE_NAME"].ToString(); values. Alternatively, you can try OpenXML SDK: How to: Parse and read a large spreadsheet document (Open XML SDK)

When you define print area in your sheet "_xlnm.Print_Area" automatic added with your new sheet. Please remove print area form excel sheet or use following code

if (!dr["TABLE_NAME"].ToString().Contains("_xlnm#Print_Area"))
{    
   obj.SheetName = dr["TABLE_NAME"].ToString();
   lst.Add(obj);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM