DataSet导出到Excel(winform)

 public static void ExportToExcel(DataSet dataSet,string fileName)
        {

            try
            {
                string saveFileName = string.Empty;
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0return//被点了取消 
                Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                excelApp.DisplayAlerts = false;//保存时不提示     
                System.Diagnostics.Process[] xlPrcArray;
                xlPrcArray = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                //确定新建Excel文件的进程   
                System.Diagnostics.Process newExcelPrc = xlPrcArray[0];
                for (int i = 0; i <= xlPrcArray.Length - 1; i++)
                {
                    if (xlPrcArray[i].TotalProcessorTime.TotalSeconds < newExcelPrc.TotalProcessorTime.TotalSeconds)
                    {
                        newExcelPrc = xlPrcArray[i];
                    }
                }
                // Create a new Excel Workbook   
                Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
                int sheetIndex = 0;
                // Copy each DataTable   
                foreach (System.Data.DataTable dt in dataSet.Tables)
                {
                    // Copy the DataTable to an object array   
                    object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
                    // Copy the column names to the first row of the object array   
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        rawData[0, col] = dt.Columns[col].ColumnName;
                    }
                    // Copy the values to the object array   

                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        //字符型前面要加上:'   
                        if (dt.Columns[col].DataType == System.Type.GetType("System.String"))
                        {
                            for (int row = 0; row < dt.Rows.Count; row++)
                            {
                                rawData[row + 1, col] = "'" + dt.Rows[row].ItemArray[col].ToString();
                            }
                        }
                        else
                        {
                            for (int row = 0; row < dt.Rows.Count; row++)
                            {
                                rawData[row + 1, col] = dt.Rows[row].ItemArray[col].ToString();
                            }
                        }
                    }
                    // Calculate the final column letter   
                    string finalColLetter = string.Empty;
                    string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    int colCharsetLen = colCharset.Length;
                    if (dt.Columns.Count > colCharsetLen)
                    {
                        finalColLetter = colCharset.Substring(
                            (dt.Columns.Count - 1) / colCharsetLen - 11);
                    }
                    finalColLetter += colCharset.Substring(
                            (dt.Columns.Count - 1) % colCharsetLen, 1);
                    // Create a new Sheet   
                    Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
                        excelWorkbook.Sheets.get_Item(++sheetIndex),
                        Type.Missing, 1, XlSheetType.xlWorksheet);
                    excelSheet.Name = dt.TableName;
                    // Fast data export to Excel   
                    string excelRange = string.Format("A1:{0}{1}",
                        finalColLetter, dt.Rows.Count + 1);
                    excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
                    // Mark the first row as BOLD   
                    ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
                }
                // Save and Close the Workbook   

                excelWorkbook.SaveAs(saveFileName, XlFileFormat.xlWorkbookNormal, Type.Missing,

                    Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,

                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                excelWorkbook.Close(true, Type.Missing, Type.Missing);

                excelWorkbook = null;
                //// Release the Application object   
                excelApp.Quit();

                excelApp = null;
                // Collect the unreferenced objects   

                GC.Collect();

                GC.WaitForPendingFinalizers();
                newExcelPrc.Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
posted @ 2012-09-05 14:17  青春岁月,无怨无悔  阅读(365)  评论(0编辑  收藏  举报