简体   繁体   English

在 C# 中使用 OleDbConnection 读取 Excel 工作表时数据丢失

[英]Data missing while Reading Excel sheet using OleDbConnection in C#

I need to read the excel data and store in database.我需要读取excel数据并存储在数据库中。 when I try to read the data, there are some data got missed, I couldn't able to find.当我尝试读取数据时,有一些数据丢失了,我无法找到。

It's my excel sheet这是我的excel表在此处输入图片说明

My code :我的代码:

private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";

 [![//Get the name of the First Sheet.
            using (OleDbConnection con = new OleDbConnection(conStr))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = con;
                    con.Open();
                    DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    sheetName = dtExcelSchema.Rows\[0\]\["TABLE_NAME"\].ToString();
                    con.Close();
                }
            }

            //Read Data from the First Sheet.
            using (OleDbConnection con = new OleDbConnection(conStr))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    using (OleDbDataAdapter oda = new OleDbDataAdapter())
                    {

                        cmd.CommandText = "SELECT * From \[" + sheetName + "\]";
                        cmd.Connection = con;
                        con.Open();
                        oda.SelectCommand = cmd;
                        oda.Fill(dtExcelData);
                        con.Close();

                        //Populate DataGridView.
                        //dataGridView1.DataSource = dt;
                    }
                }
            }

            dtExcelData = dtExcelData.AsEnumerable().Skip(2).Take(1).CopyToDataTable();

            return dtExcelData;][2]][2]

Data after reading through in oledbConnection :在 oledbConnection 中通读后的数据:

在此处输入图片说明

You have some merged cell in your excel Sheet , it's better to access your cells directly您的 excel 表中有一些合并的单元格,最好直接访问您的单元格

I think here also can help you:我认为这里也可以帮助您:

Excel - Reading Merged Cells (rows) in .NET using C# Excel - 使用 C# 在 .NET 中读取合并的单元格(行)

You can use this class to your project easily;您可以轻松地将此类用于您的项目; https://exceldatareader.codeplex.com/ https://exceldatareader.codeplex.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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