需要添加引用 Microsoft.Office.Interop.Excel
注意:使用Microsoft.Office.Interop.Excel 非常耗時。對性能有要求建議用其他。
如果要用,把數據轉成字符串拷貝到剪貼板中,然后把剪貼板數據粘貼到sheet表中即可,幾十萬數據秒級。下面有講到怎么轉換字符串拷貝與粘貼。

代碼部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*******************************************************************
* Copyright (C) 版權所有
* 文件名稱:ExcelManage
* 命名空間:WindowsFormsApplication3
* 創建時間:2019/3/4 15:20:27
* 作 者: wangyonglai
* 描 述:
* 修改記錄:
* 修改人:
* 版 本 號:v1.0.0
**********************************************************************/
namespace WindowsFormsApplication3
{
//替代名稱
using Excel = Microsoft.Office.Interop.Excel;//替代名稱
using Missing = System.Reflection.Missing;
class ExcelManage
{
public System.Data.DataSet dataSet = new System.Data.DataSet();
public void InitalTable()
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("序號", typeof(int));
table.Columns.Add("數據1", typeof(int));
table.Columns.Add("數據2", typeof(int));
Random r = new Random();
for (int i = 0; i < 200; i++)
{
if (i == 6 || i == 16) continue;
table.Rows.Add(i + 1, r.Next(50), r.Next(60));
}
dataSet.Tables.Add(table);
//ExportExcel(dataSet);
}
public void ExportExcel(System.Data.DataSet ds)
{
//新建EXCEL應用
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
return;
//設置為不可見,操作在后台執行,為 true 的話會打開 Excel
excelApp.Visible = false;
//初始化工作簿
Excel.Workbooks workbooks = excelApp.Workbooks;
//新增加一個工作簿,Add()方法也可以直接傳入參數 true
//Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//同樣是新增一個工作簿,但是會彈出保存對話框
Excel.Workbook workbook = workbooks.Add(true);
//Excel.Worksheet c_worksheet = workbook.Worksheets[1];
//int a = workbook.Worksheets.Count;
//workbook.Sheets.Add(Missing.Value, workbook.Sheets[1], ds.Tables.Count - 1, Missing.Value);
for (int index = 0; index < ds.Tables.Count; index++)
{
System.Data.DataTable dt = ds.Tables[index];
Excel.Worksheet worksheet = workbook.Worksheets.Add();
//Excel.Worksheet worksheet = workbook.Worksheets[index + 1];
//創建一個單元格
Excel.Range range;
int rowIndex = 1; //行的起始下標為 1
int colIndex = 1; //列的起始下標為 1
for (int i = 0; i < dt.Columns.Count; i++)
{
//設置第一行,即列名
worksheet.Cells[rowIndex, colIndex + i] = dt.Columns[i].ColumnName;
//獲取第一行的每個單元格
range = worksheet.Cells[rowIndex, colIndex + i];
//字體加粗
range.Font.Bold = true;
//設置為黑色
range.Font.Color = 0;
//設置為宋體
range.Font.Name = "Arial";
//設置字體大小
range.Font.Size = 12;
//水平居中
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//垂直居中
range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
}
//跳過第一行,第一行寫入了列名
rowIndex++;
//寫入數據
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[rowIndex + i, colIndex + j] = dt.Rows[i][j].ToString();
range = worksheet.Cells[rowIndex + i, colIndex + j];
range.Interior.Color = System.Drawing.Color.Yellow;
range.Cells.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.Weight = Excel.XlBorderWeight.xlHairline;//邊框常規粗細
}
}
//設置所有單元格列寬為自動列寬
worksheet.Cells.Columns.AutoFit();
#region 凍結行
worksheet.Select();
excelApp.ActiveWindow.SplitRow = 1;
excelApp.ActiveWindow.SplitColumn = 0;
excelApp.ActiveWindow.FreezePanes = true;
#endregion
#region 合並行
//Excel.Range mergeRange = worksheet.get_Range("A25", "B25");
//mergeRange.Merge();
/////合並單元格之后,設置其中的文本
//mergeRange.Value = "mergeRange";
#endregion
#region 繪制CHART圖表
int num = dt.Rows.Count + 1;
Excel.Chart xlChart = workbook.Charts.Add(Missing.Value, Missing.Value, 1, Missing.Value);
Excel.Range ranges1 = worksheet.Cells[1, 1];
Excel.Range ranges2 = worksheet.Cells[num, dt.Columns.Count];
Excel.Range chartRage = worksheet.get_Range(ranges1, ranges2);
xlChart.ChartWizard(chartRage, Excel.XlChartType.xlLine, Missing.Value,
Excel.XlRowCol.xlColumns, 1, 1,
Missing.Value, Missing.Value, "X值", "Y值", Missing.Value);
workbook.ActiveChart.HasTitle = true;
workbook.ActiveChart.ChartTitle.Text = "圖表名稱";
workbook.ActiveChart.HasDataTable = false;
//給圖表放在指定位置
//workbook.ActiveChart.Location(Excel.XlChartLocation.xlLocationAsObject, worksheet.Name);
xlChart.Name = "CC1";
#endregion
//workbook.Worksheets.Item(
}
//是否提示,如果想刪除某個sheet頁,首先要將此項設為fasle。
excelApp.DisplayAlerts = false;
//保存寫入的數據,這里還沒有保存到磁盤
workbook.Saved = true;
workbook.SaveCopyAs(@"C:\Users\Lenovo\Desktop\sample.xlsx");
workbook.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
workbook = null;
//worksheet = null;
//shapeSheet = null;
excelApp = null;
GC.Collect();
}
}
}
效果


最后由於此方法寫入時非常耗時,我們可以采用先把數據轉成字符串拷貝到剪貼板中,然后在復制到sheet表中,這樣十萬數據只要幾秒鍾
代碼
public void ExportExcel()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("序號", typeof(int));
dt.Columns.Add("數據1", typeof(int));
dt.Columns.Add("數據2", typeof(int));
Random r = new Random();
for (int i = 0; i < 20000; i++)
{
if (i == 6 || i == 16) continue;
dt.Rows.Add(i + 1, r.Next(50), r.Next(60));
}
StringBuilder strbu = new StringBuilder();
//寫入標題
for (int i = 0; i < dt.Columns.Count; i++)
{
strbu.Append(dt.Columns[i].ColumnName.ToString() + "\t");
}
//加入換行字符串
strbu.Append(Environment.NewLine);
//寫入內容
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
strbu.Append(dt.Rows[i][j].ToString() + "\t");
}
strbu.Append(Environment.NewLine);
}
System.Windows.Forms.Clipboard.SetText(strbu.ToString());
//新建EXCEL應用
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
return;
//設置為不可見,操作在后台執行,為 true 的話會打開 Excel
excelApp.Visible = false;
//初始化工作簿
Excel.Workbooks workbooks = excelApp.Workbooks;
//新增加一個工作簿,Add()方法也可以直接傳入參數 true
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//同樣是新增一個工作簿,但是會彈出保存對話框
//Excel.Workbook workbook = workbooks.Add(true);
//Excel.Worksheet worksheet = workbook.Worksheets[1];
Excel.Worksheet worksheet = workbook.Worksheets.Add();
//Excel.Range ranges1 = worksheet.Cells[1, 1];
//Excel.Range ranges2 = worksheet.Cells[dt.Rows.Count + 1, dt.Columns.Count];
//Excel.Range chartRage = worksheet.get_Range(ranges1, ranges2);
//Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[dt.Rows.Count+1, dt.Columns.Count]);
//chartRage.Copy(strbu.ToString());
//ranges1.Value = System.Windows.Forms.Clipboard.GetText();
//worksheet.Activate();
worksheet.Paste();
//worksheet.PasteSpecial(System.Windows.Forms.Clipboard.GetText(), false, false);
//新建一個 Excel 文件
string filePath = @"C:\Users\Lenovo\Desktop\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
//創建文件
FileStream file = new FileStream(filePath, FileMode.CreateNew);
//關閉釋放流,不然沒辦法寫入數據
file.Close();
file.Dispose();
//保存寫入的數據,這里還沒有保存到磁盤
workbook.Saved = true;
//保存到指定的路徑
workbook.SaveCopyAs(filePath);
}
private void WriteDataToExcel { Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); DataTable dataTable1 = this.GetTabel1();//獲取表格2 Microsoft.Office.Interop.Excel.Application excelApp; Microsoft.Office.Interop.Excel._Workbook workBook; Microsoft.Office.Interop.Excel._Worksheet workSheet; Microsoft.Office.Interop.Excel._Worksheet workSheet1; object misValue = System.Reflection.Missing.Value; workBook = excelApp.Workbooks.Add(misValue);//加載模型 workSheet = (Microsoft.Office.Interop.Excel._Worksheet)workBook.Sheets.get_Item(1);//第一個工作薄。 workSheet1 = (Microsoft.Office.Interop.Excel._Worksheet)workBook.Sheets.get_Item(2); int rowIndex = 0; int colIndex = 0; foreach (DataRow row in dataTable.Rows) { rowIndex++; colIndex = 0; foreach (DataColumn col in dataTable.Columns) { colIndex++; workSheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString().Trim(); } } rowIndex = 0; colIndex = 0; foreach (DataRow row in dataTable1.Rows) { rowIndex++; colIndex = 0; foreach (DataColumn col in dataTable1.Columns) { colIndex++; workSheet1.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString().Trim(); } } workSheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing); //保護工作表 workSheet1.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing); /**/ excelApp.Visible = false; workBook.SaveAs(@"D:\outputFormDataBase1.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); dataTable = null; workBook.Close(true, misValue, misValue); excelApp.Quit(); PublicMethod.Kill(excelApp);//調用kill當前excel進程 }
有興趣的可以看看 https://www.cnblogs.com/junshijie/p/5292087.html 這篇文章,里面有更詳細如何操作EXCEL。
