您的位置:首页 > 编程语言 > C#

C#winForm导出excel

2012-12-03 12:38 573 查看
//引用
using System.Windows.Forms;
using System.Data.OleDb;

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel file(*.xls)|*.xls";
sfd.Title = CliUtils.GetMessage("exporttitle");
sfd.AddExtension = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
ExportExcel(sfd.FileName);
}

private void ExportExcel(string path)
{
//根据模板导出
string _fileName = string.Format(@"{0}\{1}", Application.StartupPath, "ImportTemplate.xls");
if (!File.Exists(_fileName))
{
MessageBox.Show("客户端找不到导出模板文件");
return;
}
try
{
File.Copy(_fileName, path, true);
}
catch
{
MessageBox.Show(CliUtils.GetMessage("exportuse"));
return;
}
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;'";//IMEX=1
OleDbConnection OleConn = new OleDbConnection(strConn);
OleConn.Open();

OleDbCommand comm;
int count = 0;
try
{
for (int i = 0; i < dataSet1.Tables[1].Rows.Count; i++)
{
string sql = string.Format("  Insert into [Sheet1$] values ('{0}',{1})  ", new object[]{
dataSet1.Tables[1].Rows[i]["value"],dataSet1.Tables[1].Rows[i]["qty"]});
comm = new OleDbCommand(sql, OleConn);
comm.ExecuteNonQuery();
count++;
}

}
catch
{
MessageBox.Show("文件正在被使用");
return;
}
finally
{
OleConn.Close();
}

if (count > 0)
{
this.Close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# winform 导出 excel