public bool ExportDataGridViewToExcel(DataGridView dgv, bool isShowExcel)//将DataGridView中的数据导入到Excel中 2010年7月5日
{
if (dgv.Rows.Count == 0)
return false;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcel;
for (int i = 0; i < dgv.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
}
for (int j = 0; j < dgv.Rows.Count - 1; j++)
{
for (int k = 0; k < dgv.Columns.Count; k++)
{
if (dgv[k, j].ValueType == typeof(string))
{
excel.Cells[j + 2, k + 1] = "'" + dgv[k, j].Value.ToString();
}
else
{
excel.Cells[j + 2, k + 1] = dgv[k, j].Value.ToString();
}
}
}
return true;
}
导出Excel按钮直接调用此方法
private void button1_Click(object sender, EventArgs e)//数据导出到Excel按钮
{
UserService us = new UserService();//定义ExportDataGridViewToExcel方法的类
us.ExportDataGridViewToExcel(dataGridView1, true);//dataGridView1为界面上添加的一个控件
}
private void frmGlYwjReport_Load(object sender, EventArgs e)
{
GlYwjReportService glYwjReportService = new GlYwjReportService();
this.WindowState = FormWindowState.Normal;
dataGridView1.Columns.Clear();
dataGridView1.DataSource = glYwjReportService.getAllReport();
}
public DataTable getAllReport()//用于查询全部
{
DataTable allReport = new DataTable();
allReport = glYwjReportDao.selectAll();
return allReport;
}
public DataTable selectAll()//查询信息计量部需要的所有数据,即全部按钮的数据
{
DataTable dt = new DataTable();
OracleConnection conn = ODBCConnectionFactory.getConnection2();
try
{
string strSql = "色了传统";
OracleDataAdapter da = new OracleDataAdapter(strSql, conn);
Console.WriteLine(strSql, "ironout");
da.Fill(dt);
conn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return dt;
}