C#实现Excel模板导出和从Excel导入数据
2015-10-29 13:47
746 查看
午休时间写了一个Demo关于Excel导入导出的简单练习
1.窗体
View Code
5.演示
6.源代码下载
1.窗体
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ExcelDemo { /// <summary> /// 针对Excel写的帮助模型 /// </summary> public partial class Form1 : Form { #region 变量 /// <summary> /// 导出模板列集合 /// </summary> List<string> columnListOut = new List<string>() { "列1", "列2", "列3", "列4" }; /// <summary> /// 导出模板文件名称 /// </summary> string FileName = "导出模板"; /// <summary> /// Excel底层页签名称 /// </summary> string SheetName = "Excel页签名称"; /// <summary> /// ExcelHelper实例化 /// </summary> ExcelHelper excelHelper = new ExcelHelper(); #endregion #region 初始化、数据加载 public Form1() { InitializeComponent(); } #endregion #region 控件事件 /// <summary> /// 选择文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnChooseFile_Click(object sender, EventArgs e) { //对于选择文件转化的DataTable和提示信息msg的委托 Action<string, DataTable> action = new Action<string, DataTable>((string str, DataTable dt) => { if (dt == null || dt.Rows.Count == 0) { MessageBox.Show("dt为空的"); return; } if (dt.Rows.Count > 1000) { MessageBox.Show("导入的数据已超过最大限制1000条"); return; } if (!this.columnListOut.ToArray().All(t => dt.Columns.Contains(t))) { MessageBox.Show("导入的数据字段不匹配"); return; } //获取列1的可枚举集合 IEnumerable<string> column1List = dt.Rows.Cast<DataRow>().Select(r => r["列1"].ToString()); //验证列1必须是整数切不能是负数 decimal isDecimal = 0; foreach (var item in column1List) { if ((!decimal.TryParse(item, out isDecimal)) && !string.IsNullOrEmpty(item)) { MessageBox.Show("列1必须是Decimal类型"); return; } if (isDecimal < 0) { MessageBox.Show("列1不允许是负数"); return; } } dt.AcceptChanges(); this.dgv.DataSource = dt; }); this.excelHelper.ImportExcelToDataTable(this, action, this.SheetName); } /// <summary> /// 导出模板 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOut_Click(object sender, EventArgs e) { string[] columnList = this.columnListOut.ToArray(); string msg = string.Empty; this.excelHelper.SaveExcelTemplate(columnList, this.FileName, this.SheetName, ref msg); } #endregion } }
View Code
5.演示
6.源代码下载
相关文章推荐
- C#中get和set
- 黄聪:C#超级延时方法,延迟系统时间但系统又能同时能执行其它任务
- C#冒泡排序
- C# 关于用7zip压缩文件提示win32exception 系统找不到文件解决方案(win7 x64)
- 2.C# Thread初识
- C#语句先后顺序对程序的结果有影响吗
- C#无锁内存队列
- c#中语句的先后顺序对结果的影响
- C#多线程中子线程快速终止的几个处理办法
- C# 多线程方式 Thread Delegate
- C#操作符??和?:
- C#中Serializable序列化
- C#使用RDP远程桌面
- C#继承
- Leetcode-134-Gas Station C#
- C# 最简单实现文件附件在线预览的方法
- C# 下载多个文件打zip包的问题
- C# 下载文件名重命名的问题
- C#获取IP及MAC地址 方法
- c#面向对象