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.IO;
namespace exce
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// DatadataGridView1 dataGridView1 = new DatadataGridView1();
DataSet objSet = new DataSet();
private static DataSet _objSet;
public static DataSet ObjSet
{
get { return Form1._objSet; }
set { Form1._objSet = value; }
}
private void button1_Click(object sender, EventArgs e)
{
// datadataGridView11
//dataGridView1
if (dataGridView1.Rows.Count==0)
{
MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
saveFileDialog1.Filter = "Execl files (*.xlsx)|*.xlsx";
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.Title = "导出文件保存路径";
saveFileDialog1.ShowDialog();
string strName = saveFileDialog1.FileName;
if (strName.Length != 0)
{
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Application.Workbooks.Add(true); ;
excel.Visible = false;//若是true,则在导出的时候会显示EXcel界面。
if (excel == null)
{
MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
sheet.Name = "test";
//生成字段名称
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText.ToString();
}
//填充数据
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (dataGridView1[j, i].Value == typeof(string))
{
excel.Cells[i + 2, j + 1] = "" + dataGridView1[i, j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
}
sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(false, miss, miss);
books.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
MessageBox.Show("数据已经成功导出到:" + saveFileDialog1.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
去51aspx.com找去,有免费的!更多功能的源代码也有!