DataGridView 数据表导出Excel(之一)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Reporting.WinForms;
using System.IO;
namespace MicroTools
{
public partial class toExcel : Form
{
public toExcel()
{
InitializeComponent();
}
private void but_run_Click(object sender, EventArgs e)
{
//AcceptButton = this.but_run;
this.usp_testTableAdapter.Fill(employeeDataSet.usp_test,this.comboBox1.Text,this.comboBox2.Text);
this.but_run.Focus();
}
public bool exportDataGridview(DataGridView dataGridView1)
{
if (dataGridView1.RowCount==0)
return false;
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "" + dataGridView1[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
}
return true;
}
private void export1_Click(object sender, EventArgs e)
{
this.exportDataGridview(dataGridView1);
}
}
}
引用中要最起码添加 office.core 、Excel引用