C#读取Excel写入数据库/将 Excel 文件转成 DataTable

#region 读取Excel


        /// <summary>
        /// 将 Excel 文件转成 DataTable 后,再把 DataTable中的数据写入表Products
        /// </summary>
        /// <param name="serverMapPathExcelAndFileName"></param>
        /// <param name="excelFileRid"></param>
        /// <returns></returns>
        public static int WriteExcelToDataBase(string excelFileName)
        {
            int rowsCount = 0;
            OleDbConnection objConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFileName+ ";" + "Extended Properties=Excel 8.0;");
            objConn.Open();
            try
            {
                DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                string sheetName = string.Empty;
                for (int j = 0; j < schemaTable.Rows.Count; j++)
                {
                    sheetName = schemaTable.Rows[j][2].ToString().Trim();//获取 Excel 的表名,默认值是sheet1 
                    DataTable excelDataTable = DbHelperSQL.ExcelToDataTable(excelFileName, sheetName, true);
                    if (excelDataTable.Columns.Count > 1)
                    {
                          SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
                            sqlbulkcopy.DestinationTableName = "Products";//数据库中的表名


                            sqlbulkcopy.WriteToServer(excelDataTable);
                            sqlbulkcopy.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                objConn.Close();
                objConn.Dispose();
            }
            return rowsCount;
        }


 /// <summary>
        /// 读取Excel
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static DataSet ExcelToDS(string Path, string sheetName)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";  //HDR=Yes;
            DataSet ds = null;
            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                OleDbDataAdapter myCommand = null;
                try
                {
                    conn.Open();
                    string strExcel = "";
                    strExcel = "select * from [" + sheetName + "$]";
                    myCommand = new OleDbDataAdapter(strExcel, strConn);
                    ds = new DataSet();
                    myCommand.Fill(ds, "table1");
                }
                catch (SqlException ex)
                {
                    throw ex;
                }
                finally
                {
                    myCommand.Dispose();
                    conn.Close();
                }
                return ds;
            }
        }


        /// <summary>
        /// 将 Excel 文件转成 DataTable
        /// </summary>
        /// <param name="serverMapPathExcel">Excel文件及其路径</param>
        /// <param name="strSheetName">工作表名,如:Sheet1</param>
        /// <param name="isTitleOrDataOfFirstRow">True 第一行是标题,False 第一行是数据</param>
        /// <returns>DataTable</returns>
        public static DataTable ExcelToDataTable(string serverMapPathExcel, string strSheetName, bool isTitleOrDataOfFirstRow)
        {


            string HDR = string.Empty;//如果第一行是数据而不是标题的话, 应该写: "HDR=No;"
            if (isTitleOrDataOfFirstRow)
            {
                HDR = "YES";//第一行是标题
            }
            else
            {
                HDR = "NO";//第一行是数据
            }
            //源的定义 
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + serverMapPathExcel + ";" + "Extended Properties='Excel 8.0;HDR=" + HDR + ";IMEX=1';";


            //Sql语句
            //string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
            string strExcel = "select * from   [" + strSheetName + "]";
            //定义存放的数据表
            DataSet ds = new DataSet();


            //连接数据源
            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                try
                {
                    conn.Open();
                    //适配到数据源
                    OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
                    
                    adapter.Fill(ds, strSheetName);
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw ex;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
            return ds.Tables[strSheetName];
        }
        #endregion

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要将 Excel 表格写入 MDB 文件(Microsoft Access 数据库文件),你可以使用 C# 中的 OleDbConnection 和 OleDbDataAdapter 类来实现。下面是一个示例代码: ```csharp using System; using System.Data; using System.Data.OleDb; namespace ExcelToMDB { class Program { static void Main(string[] args) { string excelFilePath = @"path\to\your\excel\file.xlsx"; string mdbFilePath = @"path\to\your\mdb\file.mdb"; string excelConnectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={excelFilePath};Extended Properties='Excel 12.0 Xml;HDR=YES;'"; string mdbConnectionString = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={mdbFilePath}"; using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString)) using (OleDbConnection mdbConnection = new OleDbConnection(mdbConnectionString)) { try { excelConnection.Open(); mdbConnection.Open(); // 从 Excel 表格中读取数据 string selectQuery = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectQuery, excelConnection); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); // 将数据写入 MDB 文件 using (OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter)) { dataAdapter.InsertCommand = commandBuilder.GetInsertCommand(); dataAdapter.Update(dataTable); Console.WriteLine("Data written to MDB file successfully!"); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } } } ``` 在上面的代码中,你需要将 `path\to\your\excel\file.xlsx` 替换为实际的 Excel 文件路径,将 `path\to\your\mdb\file.mdb` 替换为实际的 MDB 文件路径。 首先,使用 `Microsoft.ACE.OLEDB.12.0` 提供程序创建一个连接字符串来连接到 Excel 文件。然后,使用 `Microsoft.Jet.OLEDB.4.0` 提供程序创建一个连接字符串来连接到 MDB 文件。 接下来,使用 OleDbConnection 打开 Excel 和 MDB 的连接。 然后,使用 OleDbDataAdapter 从 Excel 表格中读取数据,并将其填充到一个 DataTable 中。 最后,使用 OleDbCommandBuilder 创建插入命令,并使用 OleDbDataAdapter 的 Update 方法将数据写入 MDB 文件。 请确保你的系统中安装了适当的 OLEDB 提供程序(如 `Microsoft.ACE.OLEDB.12.0`)和相应的驱动程序。 希望这能满足你的需求!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值