通过DataTable导出Excel文件



#region 导出为EXCEL

        //第一种方法是直接导出Excel。
        /// <summary>
        /// 将DataTable或DataSet导出为Excel
        /// 修改  2016/7/6
        /// </summary>
        /// <param name="dt">需要导出的DataTable,DataSet或GridView</param>
        /// <param name="AbosultedFilePath">Excel的绝对路径</param>
        /// <returns>是否成功</returns>
        public static bool ExportToExcel(System.Data.DataTable dt, string AbosultedFilePath)
        {
            if (dt == null)
                return false;
            // 创建Excel应用程序对象
            Microsoft.Office.Interop.Excel.Application excApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workBook = excApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSeet = workBook.Worksheets[1]; //取得sheet1
            Microsoft.Office.Interop.Excel.Range range = null;
            int tableCount = dt.Rows.Count;
            int rowRead = 0;
            float percent = 0;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                workSeet.Cells[1, i + 1] = dt.Columns[i].ColumnName;

                //设置标题的样式
                range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[1, i + 1];
                range.Font.Bold = true; //粗体
                range.Font.Size = "12";//字体大小
                range.Font.Name = "宋体";
                range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //居中
                range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //背景色
                range.EntireColumn.AutoFit(); //自动设置列宽
                range.EntireRow.AutoFit(); //自动设置行高
               
            }
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int c = 0; c < dt.Columns.Count; c++)
                {
                    //写入内容
                    workSeet.Cells[r + 2, c + 1] = "'" + dt.Rows[r][c].ToString();
                    //设置样式
                    range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[r + 2, c + 1];
                    range.Font.Size = 9; //字体大小
                    range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //加边框
                    range.EntireColumn.AutoFit(); //自动调整列宽
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / tableCount;
                System.Windows.Forms.Application.DoEvents();
            }
            range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
            if (dt.Columns.Count > 1)
            {
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
            }
            try
            {
                workBook.Saved = true;
                workBook.SaveCopyAs(AbosultedFilePath);
            }
            catch { }
            workBook.Close();
            if (excApp != null)
            {
                excApp.Workbooks.Close();
                excApp.Quit();
                int generation = System.GC.GetGeneration(excApp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excApp);
                excApp = null;
                System.GC.Collect(generation);
            }
            GC.Collect(); //强行销毁
            #region 强行杀死最近打开的Excel进程
            System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            System.DateTime startTime = new DateTime();
            int m, killID = 0;
            for (m = 0; m < excelProc.Length; m++)
            {
                if (startTime < excelProc[m].StartTime)
                {
                    startTime = excelProc[m].StartTime;
                    killID = m;
                }
            }
            if (excelProc[killID].HasExited == false)
            {
                excelProc[killID].Kill();
            }
            #endregion
            return true;
        }






        //第二种方法为通过设置好的模板在导出Excel。
        /// <summary>   
        /// 把table中的数据导出到excel中去   
        /// </summary>   
        /// <param name="dt">要导入的table</param>   
        /// <param name="maxcount">模板excel中,一个sheet要显示的行数,如果数据多一个sheet中的最大值,会自动生成新的sheet</param>
        private void ExportExcel(System.Data.DataTable dt, int maxcount, string filepath, string fileautoname)   
        {       
            Random ran = new Random();      
            object missing = Type.Missing;       
            Microsoft.Office.Interop.Excel.Application application = new Application();       
            Workbook workbook = application.Workbooks.Open(filepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);       
            Worksheet worksheet;       
            worksheet = (Worksheet)workbook.Sheets.get_Item(1);               
            DataView dv = dt.DefaultView;       
            //dv.Sort = "id asc"; //table 中的数据按id升序排列       
            System.Data.DataTable table = dv.ToTable();               
            int sheetcount = GetSheetCount(table.Rows.Count, maxcount);       
            for (int count = 1; count < sheetcount; count++)       
            {           
                ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(count)).Copy(missing, workbook.Worksheets[count]);       
            }       
            List<object[,]> list = new List<object[,]>();       
            object[,] ret;       
            for (int count = 0; count < sheetcount; count++)       
            {           
                if (count == sheetcount - 1)           
                {               
                    ret = new object[table.Rows.Count - count * maxcount, table.Columns.Count - 0];               
                    for (int i = 0; i < table.Rows.Count - count * maxcount; i++)               
                    {                    for (int j = 0; j < table.Columns.Count - 0; j++)  //修改过                 
                    {                       
                        ret[i, j] = table.Rows[count * maxcount + i][j];                   
                    }               
                    }               
                    list.Add(ret);           
                }           
                else           
                {               
                    ret = new object[maxcount, table.Columns.Count - 2];               
                    for (int i = 0; i < maxcount; i++)               
                    {                   
                        for (int j = 0; j < table.Columns.Count - 2; j++)                   
                        {                       
                            ret[i, j] = table.Rows[i + count * maxcount][j];                   
                        }               
                    }               
                    list.Add(ret);           
                }       
            }       
            object[,] obj;       
            for (int p = 0; p < list.Count; p++)       
            {           
                worksheet = (Worksheet)workbook.Sheets.get_Item(p + 1);           
                obj = list[p];           
                string cn = "G" + (obj.GetLength(0) + 1).ToString(); //设置填充区域  修改过         
                worksheet.get_Range("A2", cn).FormulaR1C1 = obj;        //修改过
            }       
            workbook.SaveAs(fileautoname, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);       
            workbook.Close(missing, missing, missing);       
            application.Quit();       
            workbook = null;
            #region 强行杀死最近打开的Excel进程
            System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            System.DateTime startTime = new DateTime();
            int m, killID = 0;
            for (m = 0; m < excelProc.Length; m++)
            {
                if (startTime < excelProc[m].StartTime)
                {
                    startTime = excelProc[m].StartTime;
                    killID = m;
                }
            }
            if (excelProc[killID].HasExited == false)
            {
                excelProc[killID].Kill();
            }
            #endregion
        }

        /// <summary>   
        ///  获取WorkSheet数量   
        /// </summary>   
        /// <param name="rowCount">记录总行数</param>   
        /// <param name="rows">每WorkSheet行数</param>   
        /// <returns></returns>   
        private int GetSheetCount(int rowCount,int rows)   
        {       
            int n = rowCount % rows;        //余数       
            if(n == 0)           
                return rowCount / rows;       
            else           
                return Convert.ToInt32(rowCount / rows) + 1;   
        }
        #endregion


        //通过Excel导出数据到DataTable
        /// <summary>
        /// 将Excel文件导入到datatable中
        /// </summary>
        /// <param name="strpath">文件路径</param>
        /// <returns></returns>
        public static DataTable ExcelTOdt(string strpath)
        {
            string FileType = strpath.Substring(strpath.IndexOf("."));
            string strConn;
           
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";Data Source=" + strpath;
            if (FileType==".xlsx")
            {
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strpath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";
            }
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.ConnectionString = strConn;
            conn.Open();
            DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

            List<string> sheetList = new List<string>();
            foreach (DataRow dr in sheetNames.Rows)
            {
                sheetList.Add(dr[2].ToString());
            }
            string sql = string.Format("select * from [{0}]", sheetList[0].ToString());
            OleDbDataAdapter ola = new OleDbDataAdapter(sql, conn);
            DataTable dt = new DataTable();
            ola.Fill(dt);
            conn.Close();

            //OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
            //DataTable dt = new DataTable();
            //myCommand.Fill(dt);
            return dt;
        }




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值