您的位置:首页 > 编程语言 > C#

C#实现Excel模板导出和从Excel导入数据

2015-10-29 13:47 746 查看
      午休时间写了一个Demo关于Excel导入导出的简单练习

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.源代码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: