Datagridview 获取到SQL数据库中的数据后,将数据导出成excel格式,报错
错误 1 命名空间“Microsoft.Office”中不存在类型或命名空间名称“Tools”。是否缺少程序集引用? C:\Users\MBC\Documents\Visual Studio 2010\Projects\Test\export\Form1.cs 13 24 export
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 System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.Internal.Performance;
using Microsoft.Office.Tools.Excel;
namespace export
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_getdata_Click(object sender, EventArgs e)
{
SqlConnection con;
con = new SqlConnection(@"server=.;uid=sa;pwd=abc;database=Northwind");
DataSet ds;
ds = new DataSet();
SqlDataAdapter sda;
con.Open();
string qurey = "select top 2 * from Orders";
sda = new SqlDataAdapter(qurey, con);
sda.Fill(ds, "Orders");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
private void btn_export_Click(object sender, EventArgs e)
{
SqlConnection con;
con = new SqlConnection(@"server=.;uid=sa;pwd=abc;database=Northwind");
DataSet ds;
ds = new DataSet();
SqlDataAdapter sda;
con.Open();
string qurey = "select top 2 * from Orders";
sda = new SqlDataAdapter(qurey, con);
sda.Fill(ds, "Orders");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
try
{
DataTabletoExcel(ds.Tables[0], "c:\\zczc1984.xls");
MessageBox.Show("成功");
}
catch (Exception ex)
{
MessageBox.Show("失败");
}
}
/// <summary>
/// 将DataGridView控件中数据导出到Excel
/// </summary>
/// <param name="gridView">DataGridView对象</param>
/// <param name="isShowExcle">是否显示Excel界面</param>
/// <returns></returns>
public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
{
if (tmpDataTable == null)
return;
int rowNum = tmpDataTable.Rows.Count;
int columnNum = tmpDataTable.Columns.Count;
int rowIndex = 1;
int columnIndex = 0;
Excel.Application xlApp = new Excel.ApplicationClass();
xlApp.DefaultFilePath = "";
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn dc in tmpDataTable.Columns)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
rowIndex++;
columnIndex = 0;
for (int j = 0; j < columnNum; j++)
{
columnIndex++;
xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
}
}
xlBook.SaveCopyAs(strFileName);
}
}
}