C#winForm导出excel

//引用
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();
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值