在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
数据是从access数据库中读取的。 点击导出按钮 去目录下找到对应的文件 代码: using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("aa"); dt.Columns.Add("bb"); DataRow dr = dt.NewRow(); dr[0] = "111"; dr[1] = "222"; dt.Rows.Add(dr); string path = AppDomain.CurrentDomain.BaseDirectory + @"" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"; if (dt2csv(dt, path, "图书信息", "编号,书名,作者,出版社")) { MessageBox.Show("导出成功,文件位置:" + path); } else { MessageBox.Show("导出失败"); } } /// <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; } } }
连接access数据库有可能会报错:未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序 win7或win8 64位下调试程序,出现这样的错误提示:未在本地计算机上注册 Microsoft.Jet.OLEDB.4.0 提供程序 源码下载连接包含access数据库文件:https://download.csdn.net/download/u012408847/10933670 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论