Beispiel #1
0
 public static void SaveDataTableToExcel(DataTable excelTable, string filePath)
 {
     Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
     try
     {
         app.Visible = false;
         Microsoft.Office.Interop.Excel.Workbook  wBook  = app.Workbooks.Add(true);
         Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
         if (excelTable.Rows.Count > 0)
         {
             int row = 0;
             row = excelTable.Rows.Count;
             int col = excelTable.Columns.Count;
             for (int i = 0; i < row; i++)
             {
                 for (int j = 0; j < col; j++)
                 {
                     string str = excelTable.Rows[i][j].ToString();
                     wSheet.Cells[i + 2, j + 1] = str;
                 }
             }
         }
         int size = excelTable.Columns.Count;
         for (int i = 0; i < size; i++)
         {
             wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
         }
         //设置禁止弹出保存和覆盖的询问提示框
         app.DisplayAlerts          = false;
         app.AlertBeforeOverwriting = false;
         //保存工作簿
         wBook.Save();
         //保存excel文件
         app.Save(filePath);
         app.SaveWorkspace(filePath);
         app.Quit();
         app = null;
     }
     catch
     {
         throw;
     }
 }
Beispiel #2
0
 public static void SaveDataTableToExcel(DataTable excelTable, string filePath)
 {
     Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
     try
     {
         app.Visible = false;
         Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
         Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
         if (excelTable.Rows.Count > 0)
         {
             int row = 0;
             row = excelTable.Rows.Count;
             int col = excelTable.Columns.Count;
             for (int i = 0; i < row; i++)
             {
                 for (int j = 0; j < col; j++)
                 {
                     string str = excelTable.Rows[i][j].ToString();
                     wSheet.Cells[i + 2, j + 1] = str;
                 }
             }
         }
         int size = excelTable.Columns.Count;
         for (int i = 0; i < size; i++)
         {
             wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
         }
         //设置禁止弹出保存和覆盖的询问提示框  
         app.DisplayAlerts = false;
         app.AlertBeforeOverwriting = false;
         //保存工作簿   
         wBook.Save();
         //保存excel文件   
         app.Save(filePath);
         app.SaveWorkspace(filePath);
         app.Quit();
         app = null;
     }
     catch
     {
         throw;
     }
 }