C# winform窗体导出数据到excel

C# winform窗体导出数据到excel_第1张图片

数据是从access数据库中读取的。

点击导出按钮

C# winform窗体导出数据到excel_第2张图片

去目录下找到对应的文件

C# winform窗体导出数据到excel_第3张图片

代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace TestReport
{
    public partial class Form1 : Form
    {
        DataTable myTable = new DataTable();
        public Form1()
        {
            InitializeComponent();
            string sqlConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\数据库\BookStor.mdb";
            OleDbConnection myConnection = new OleDbConnection(sqlConn);
            myConnection.Open();
            OleDbCommand myCommand = new OleDbCommand("select * from BookInfo order by ID", myConnection);
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = myCommand;
            DataSet myDs = new DataSet();
            adapter.Fill(myDs);
            myTable = myDs.Tables[0];
            dataGridView1.DataSource = myTable;
        }

        /// 
        /// 导出报表为Csv
        /// 
        /// DataTable
        /// 物理路径
        /// 表头
        /// 字段标题,逗号分隔
        public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
        {
            try
            {
                string strBufferLine = "";
                StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8);
                strmWriterObj.WriteLine(tableheader);
                strmWriterObj.WriteLine(columname);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strBufferLine = "";
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j > 0)
                            strBufferLine += ",";
                        strBufferLine += dt.Rows[i][j].ToString();
                    }
                    strmWriterObj.WriteLine(strBufferLine);
                }
                strmWriterObj.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// 
        /// List转DataTable
        /// 
        /// 
        /// 
        /// 
        public static DataTable ToDataTable(IEnumerable collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
            if (dt2csv(myTable, path, "图书信息", "编号,书名,作者,出版社"))
            {
                MessageBox.Show("导出成功,文件位置:" + path);
            }
            else
            {
                MessageBox.Show("导出失败");
            }
        }
    }
}

 连接access数据库有可能会报错:未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序

win7或win8 64位下调试程序,出现这样的错误提示:未在本地计算机上注册 Microsoft.Jet.OLEDB.4.0 提供程序

解决方法如下:

方法一:“设置应用程序池默认属性”/“常规”/”启用32位应用程序”,设置为 true。 

方法二:生成->配置管理器->平台->点击Any Cpu选项卡->新建->新建平台->X86。

源码下载连接包含access数据库文件:https://download.csdn.net/download/u012408847/10933670

你可能感兴趣的:(C#winform,C#导出,excel)