C# winform窗体导出数据到excel

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

点击导出按钮

去目录下找到对应的文件

代码:

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;
        }

        /// <summary>
        /// 导出报表为Csv
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="strFilePath">物理路径</param>
        /// <param name="tableheader">表头</param>
        /// <param name="columname">字段标题,逗号分隔</param>
        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;
            }
        }

        /// <summary>
        /// List转DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IEnumerable<T> 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

  • 8
    点赞
  • 105
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
C# WinForm中,可以使用DataGridView控件显示数据,并且可以将其中的数据导出Excel中。下面是导出当前页和全部数据的示例代码: 1. 导出当前页数据: ``` // 获取DataGridView中当前显示的数据 DataTable dt = new DataTable(); foreach (DataGridViewColumn column in dataGridView1.Columns) { dt.Columns.Add(column.HeaderText, column.ValueType); } foreach (DataGridViewRow row in dataGridView1.Rows) { DataRow dataRow = dt.NewRow(); foreach (DataGridViewCell cell in row.Cells) { dataRow[cell.ColumnIndex] = cell.Value; } dt.Rows.Add(dataRow); } // 导出数据Excel Excel.Application app = new Excel.Application(); Excel.Workbook workbook = app.Workbooks.Add(); Excel.Worksheet worksheet = workbook.Sheets[1]; for (int i = 0; i < dataGridView1.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; } for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString(); } } workbook.SaveAs("data.xlsx"); app.Quit(); ``` 2. 导出全部数据: ``` // 获取DataGridView中全部数据 DataTable dt = new DataTable(); foreach (DataGridViewColumn column in dataGridView1.Columns) { dt.Columns.Add(column.HeaderText, column.ValueType); } foreach (DataGridViewRow row in dataGridView1.Rows) { DataRow dataRow = dt.NewRow(); foreach (DataGridViewCell cell in row.Cells) { dataRow[cell.ColumnIndex] = cell.Value; } dt.Rows.Add(dataRow); } // 导出数据Excel Excel.Application app = new Excel.Application(); Excel.Workbook workbook = app.Workbooks.Add(); Excel.Worksheet worksheet = workbook.Sheets[1]; for (int i = 0; i < dataGridView1.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; } for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString(); } } workbook.SaveAs("data.xlsx"); app.Quit(); ``` 需要注意的是,导出数据Excel需要引用Microsoft.Office.Interop.Excel命名空间,因此需要在项目中添加对该命名空间的引用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你懂的11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值