數據不多可以用下面的方式方法,如果數據較大,不建議這樣使用,可能會比較卡
如果電腦上沒有Microsoft.Office.Interop.Excel.dll去找DLL下載站下載即可
需要先導入這個dll的引用
呈上代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
namespace 導出到execl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//綁定datagridview
private void Bind()
{
string sql = string.Format("select id, no, name, age, gender, address from stuinfo");
//getSet 方法返回的dataset所以要進行.Tables[0]
this.dataGridView1.DataSource = SQLHelpercs.getSet(SQLHelpercs.ConString, sql).Tables[0]; ;
}
/// <summary>
/// 導出excel
/// </summary>
/// <param name="fileName">要保存excel的名稱</param>
/// <param name="dg">DataGridView 的 名稱</param>
public void OutExecl(string fileName, DataGridView dg)
{
if (dg.Rows.Count > 0)//判斷datagridview是否有數據
{
string saveName = string.Empty;//聲明一個保存名稱
SaveFileDialog sgfDialog=new SaveFileDialog();//創建一個保存對象
sgfDialog.DefaultExt = "xls";//默認保存擴展名
sgfDialog.Filter = "Excel文件|*.xls";//保存文件的類型
sgfDialog.FileName = fileName;//保存的名稱
sgfDialog.ShowDialog();
saveName = sgfDialog.FileName;
if(saveName.IndexOf(":")<0)return;//點了取消
Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
if (xlapp == null)
{
MessageBox.Show("無法創建Execl!");
return;
}
Microsoft.Office.Interop.Excel.Workbooks wbs = xlapp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = wbs.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); //添加工作薄
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得 sheet1
//寫入標題
for (int i = 0; i < dg.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = dg.Columns[i].HeaderText;
}
//寫入數值
for (int r = 0; r < dg.Rows.Count; r++)
{
for (int i = 0; i < dg.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = dg.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列寬自適應
if (saveName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveName);
//fileSaved = true;
}
catch (Exception ex)
{
//fileSaved = false;
MessageBox.Show("導出文件時出錯,文件可能正被打開!\n" + ex.Message);
}
}
xlapp.Quit();
GC.Collect();//強行銷毀
MessageBox.Show(fileName + "保存成功!", "提示", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("報表為空,無表格需要導出","提示",MessageBoxButtons.OK);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Bind();
}
private void 導出到excelToolStripMenuItem_Click(object sender, EventArgs e)
{
OutExecl("cool.xls",this.dataGridView1);
}
}
}