C#读写Excel文件(三)

通过逐行逐个单元格向Excel写入数据的方式比较慢,下面介绍通过OLEDB方式向excel批量写入数据,速度可以提高很多倍。

使用OLEDB方式写入数据到excel表格

C#读写Excel文件(三)_第1张图片

【方法一】

///

/// 使用oledb快速写入数据到excel

///

///

///

static public void FastWriteToExcel2(DataTable data,string newFileName)

{

    /*

     * 注意:使用该方法,要求如下:

     * (1)将IMEX值设置为0

     * (2)excel文件newFileName已经存在

     * (3)excel文件的Sheet1中的第一行必须存在于dt一致的列名及顺序

     */

    string oledbString = string.Empty;

    string tmstr = "Extended Properties='Excel 8.0;HDR=YES;IMEX=0;'";

    try

    {

        oledbString = System.Configuration.ConfigurationManager.AppSettings["oledbString"].ToString();

        tmstr = System.Configuration.ConfigurationManager.AppSettings["ExtendedString"].ToString();

    }

    catch (Exception e)

    {

        throw e;

    }

    //string newFileName = xlsFilePath + "导出的excel文件.xlsx";

    // string newFileName = xlsFilePath + "导出的excel文件" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

 

    string cnnStr = string.Format(oledbString + "Data Source='{0}';" +

       tmstr, newFileName);

    string sql = "SELECT * FROM [Sheet1$]";

   using(OleDbConnection myConn=new OleDbConnection(cnnStr))

   {

       myConn.Open();

       OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(sql, myConn);

       DataSet myDataSet = new DataSet();

       myDataAdapter.Fill(myDataSet, "[Sheet1$]");

       myConn.Close();

       DataTable dt = myDataSet.Tables[0]; //初始化DataTable实例

       dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };//创建索引列

 

       int rowNum = data.Rows.Count;

       int colNum = data.Columns.Count;

       for (int k = 0; k < rowNum; k++)

       {

           DataRow myRow = dt.NewRow();

           for (int m = 0; m < colNum; m++) myRow[m] = data.Rows[k][m];

           dt.Rows.Add(myRow);

       }

       OleDbCommandBuilder odcb = new OleDbCommandBuilder(myDataAdapter);

       odcb.QuotePrefix = "["; 

       odcb.QuoteSuffix = "]";

 

       myDataAdapter.Update(myDataSet, "[Sheet1$]"); //更新数据集对应的表

   }

 

}

【方法二】

///

 /// 使用oledb快速写入数据到excel

 ///

 /// 数据

 /// 文件名

 static public void FastWriteToExcel(DataTable dt, string newFileName)

 {

     /*

      * 注意:使用该方法,要求如下:

      * (1)将IMEX值设置为0

      * (2)excel文件newFileName已经存在

      * (3)excel文件的Sheet1中的第一行必须存在于dt一致的列名及顺序

      */

     string oledbString = string.Empty;

     string tmstr = "Extended Properties='Excel 8.0;HDR=YES;IMEX=0;'";

     try

     {

         oledbString = System.Configuration.ConfigurationManager.AppSettings["oledbString"].ToString();

         tmstr = System.Configuration.ConfigurationManager.AppSettings["ExtendedString"].ToString();

     }

     catch (Exception e)

     {

         throw e;

     }

     //string newFileName = xlsFilePath + "导出的excel文件.xlsx";

    // string newFileName = xlsFilePath + "导出的excel文件" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

 

     string strCon = string.Format(oledbString + "Data Source='{0}';" +

        tmstr, newFileName);

     OleDbConnection oldCon = null;

     try

     {

         oldCon = new OleDbConnection(strCon);

        

         oldCon.Open();

        

             string sqlCreateSheet=string.Empty;

             using (OleDbCommand cmd=oldCon.CreateCommand())

             {

 

                 //sqlCreateSheet = string.Format("CREATE TABLE {0} (", ds.Tables[0].TableName);

                 string header = string.Empty;

                 for (int col = 0; col < dt.Columns.Count; col++)

                 {

                     header += dt.Columns[col].Caption + ",";

                     //sqlCreateSheet += string.Format("[{0}] VarChar,", ds.Tables[i].Columns[col].Caption);

                 }

                 header = header.Substring(0, header.Length - 1);

                 //sqlCreateSheet += sqlCreateSheet.Substring(0, sqlCreateSheet.Length - 1) + ")";

                 //cmd.CommandText = sqlCreateSheet;

                 //cmd.ExecuteNonQuery();//创建表

 

                 for (int row_index = 0; row_index < dt.Rows.Count; row_index++)

                 {

                     string sql = string.Format("insert into [Sheet1$]({0}) values(",header,dt.TableName);

                     for (int col_index = 0; col_index < dt.Columns.Count; col_index++)

                     {

                         sql += string.Format("'{0}',", dt.Rows[row_index][col_index].ToString());

                     }

                     sql = sql.Substring(0, sql.Length - 1) + ");";

                     cmd.CommandText = sql;

                     cmd.ExecuteNonQuery();

                 }

                

             }

        

     }

     catch (Exception e)

     {

         throw e;

     }

     finally

     {

         oldCon.Close();

     }

 }

你可能感兴趣的:(C#)