DataSet导入到Excel里,多个DataTable分成多个Sheet,Sheet以TableName命名

方法体代码如下:

        #region  DataSet导入到Excel里,多个DataTable分成多个Sheet,Sheet以TableName命名(引用Microsoft.Office.Interop.Excel 11.0)
        /// <summary>
        /// DataSet导入到Excel里,多个DataTable分成多个Sheet,Sheet名以TableName命名
        /// </summary>
        /// <param name="DS">要导入的Excel</param>
        /// <param name="FilePathAndName">要保存的路径和文件名</param>
        public static void DataSetToExcel(DataSet DS, string FilePathAndName)
        {
            string strName = FilePathAndName.Replace(@"\\", @"\").Replace(@"\\", @"\").Replace(@"\\", @"\");
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                excel.Visible = false;
                //设置禁止弹出保存和覆盖的询问提示框
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;
                //增加一个工作簿
                Microsoft.Office.Interop.Excel.Workbook book = excel.Workbooks.Add(true);
                System.Reflection.Missing miss = System.Reflection.Missing.Value;
                //添加工作表
                Microsoft.Office.Interop.Excel.Worksheet sheets = (Microsoft.Office.Interop.Excel.Worksheet)
                    book.Worksheets.Add(miss, miss, 19, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                for (int i = 0; i < DS.Tables.Count; i++)
                {
                    System.Data.DataTable table = DS.Tables[i];
                    //获取一个工作表
                    //Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets[i + 1] as Microsoft.Office.Interop.Excel.Worksheet;

                    Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets.Add(book.Worksheets[i + 1], Type.Missing, Type.Missing, Type.Missing) as Microsoft.Office.Interop.Excel.Worksheet;
                    int rowIndex = 1;
                    int colIndex = 0;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        sheet.Cells[1, colIndex] = col.ColumnName;
                    }
                    foreach (DataRow row in table.Rows)
                    {
                        rowIndex++;
                        colIndex = 0;
                        foreach (DataColumn col in table.Columns)
                        {
                            colIndex++;
                            sheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }
                    }
                    //sheet.Name = tableNames[i];
                    sheet.Name = Common.GetLegalFileName(DS.Tables[i].TableName.ToString());
                }
                //删除多余Sheet
                for (int g = 1; g <= book.Worksheets.Count; g++)
                {
                    Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets[g] as Microsoft.Office.Interop.Excel.Worksheet;

                    if (sheet.Name.Length > 5 && sheet.Name.Substring(0, 5) == "Sheet")
                    {
                        sheet.Delete();
                        g--;
                    }
                }
                //book.Save();
                book.SaveAs(strName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                book.Close(false, miss, miss);
                book = null;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                KillExcelProcess(excel);//结束Excel进程                
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }

        //using System.Runtime.InteropServices;
        [DllImport("user32.dll", SetLastError = true)]
        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        /// <summary>
        /// kill the excel.exe Process
        /// </summary>
        private static void KillExcelProcess(Microsoft.Office.Interop.Excel.Application _ApplicationClass)
        {
            try
            {
                if (_ApplicationClass != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(_ApplicationClass.Hwnd), out lpdwProcessId);
                    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch (Exception ex)
            {
                //ErrorLogManager.Log("Kill Excel Process", ex.Source, ex.StackTrace);

            }
        }

        

        #endregion

 

调用代码:

ataSet ds = new DataSet();

            string sql = "select top 5  * from Table_Table1";
            SqlDbHelper db = new SqlDbHelper();
            ds.Tables.Add(db.GetDataTable(sql));

            string sqlB = "select top 5  * from Table_Table2";
            ds.Tables.Add(db.GetDataTable(sqlB));

            string FilePathAndName = Server.MapPath("Temp.xls");
            DataSetToExcel(ds, FilePathAndName);

 

 

转载于:https://www.cnblogs.com/q149072205/archive/2013/04/09/3009424.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤来实现将一个 Excel 文件中的多个 sheet导入到数据库中的多个表: 1. 使用 C# 的 `OleDbConnection` 类连接 Excel 文件,获取数据表列表。 ```csharp string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=path/to/excel/file.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES';"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); DataTable sheetTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); foreach (DataRow row in sheetTable.Rows) { string sheetName = (string)row["TABLE_NAME"]; // ... } } ``` 2. 遍历数据表列表,使用 `OleDbDataAdapter` 和 `DataSet` 类获取每个 sheet 表的数据,并将数据插入到数据库中的对应表中。 ```csharp foreach (DataRow row in sheetTable.Rows) { string sheetName = (string)row["TABLE_NAME"]; string selectCommandText = "SELECT * FROM [" + sheetName + "]"; using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommandText, connection)) { DataSet dataSet = new DataSet(); adapter.Fill(dataSet); DataTable table = dataSet.Tables[0]; // 将 table 中的数据插入到数据库中的对应表中 // ... } } ``` 3. 在插入数据时,需要先创建对应的表结构。可以通过 `OleDbDataReader` 类获取每个 sheet 表的列信息,并根据列信息创建数据库表。 ```csharp string selectCommandText = "SELECT * FROM [" + sheetName + "]"; using (OleDbCommand command = new OleDbCommand(selectCommandText, connection)) using (OleDbDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo)) { DataTable schemaTable = reader.GetSchemaTable(); // 根据 schemaTable 中的信息创建数据库表 // ... } ``` 4. 插入数据时,可以使用 ADO.NET 中的 `SqlCommand` 类和 `SqlBulkCopy` 类实现高效的批量插入。 ```csharp string insertCommandText = "INSERT INTO TableName (Column1, Column2, Column3) VALUES (@Column1, @Column2, @Column3)"; using (SqlConnection sqlConnection = new SqlConnection(connectionString)) using (SqlCommand sqlCommand = new SqlCommand(insertCommandText, sqlConnection)) using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnection)) { sqlConnection.Open(); // 设置 sqlCommand 的参数 sqlCommand.Parameters.AddWithValue("@Column1", value1); sqlCommand.Parameters.AddWithValue("@Column2", value2); sqlCommand.Parameters.AddWithValue("@Column3", value3); // 设置 bulkCopy 的 DestinationTableName 和 ColumnMappings bulkCopy.DestinationTableName = "TableName"; bulkCopy.ColumnMappings.Add("Column1", "Column1"); bulkCopy.ColumnMappings.Add("Column2", "Column2"); bulkCopy.ColumnMappings.Add("Column3", "Column3"); bulkCopy.WriteToServer(table); } ``` 以上是将一个 Excel 文件中的多个 sheet导入到数据库中的多个表的大致思路,具体实现还需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值