C#实现Excel模板导出和从Excel导入数据
午休时间写了一个Demo关于Excel导入导出的简单练习
1.窗体
2.引用office命名空间
添加引用-程序集-扩展-Microsoft.Office.Interop.Excel
3.封装的ExcelHelper.cs关键类
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace ExcelDemo
{
/// <summary>
/// Excel帮助类
/// string column = "商品编码,商品名称,刊登单号,门店名称";
/// 导入数据
/// var action = new Action<string, DataTable>((str, dtExcel) =>
/// {
/// this.dgvData.DataSource = dtExcel;
/// });
/// excelHelper.ImportExcelToDataTable(this, action, "Ebay侵权下线");
/// 导出模版
/// string message = string.Empty;
// excelHelper.SaveExcelTemplate(column.Split(','), "Ebay侵权下线", "Ebay侵权下线", ref message);
/// </summary>
public class ExcelHelper
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); /// <summary>
/// 保存Excel模版
/// </summary>
/// <param name="columns">列名,例如:商品编码,商品名称,刊登单号,门店名称</param>
/// <param name="FileName">文件名,例如:Ebay侵权下线</param>
/// <param name="SheetName">工作表名称,例如:Ebay侵权下线</param>
/// <param name="message">错误信息</param>
public void SaveExcelTemplate(string[] columns, string FileName, string SheetName, ref string message)
{
string Filter = "Excel文件|*.csv|Excel文件|*.xls|Excel文件|*.xlsx"; SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.FileName = FileName;
saveFileDialog1.Filter = Filter;
saveFileDialog1.FilterIndex = ;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.Title = "Excel文件";
saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory(); if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return; //获得文件路径
string localFilePath = saveFileDialog1.FileName.ToString();
if (Regex.IsMatch(localFilePath, @"\.csv$"))
{
localFilePath = Regex.Replace(saveFileDialog1.FileName, @"\.csv$", "", RegexOptions.IgnoreCase) + ".csv";
File.WriteAllText(localFilePath, string.Join(",", columns), Encoding.Default);
}
else
{
//获取文件路径,不带文件名
ArrayToExcelTemplate(columns, localFilePath, SheetName, ref message);
} if (string.IsNullOrEmpty(message))
MessageBox.Show("\n\n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
} /// <summary>
/// 导出模版
/// </summary>
/// <param name="columns">列名,例如:商品编码,商品名称,刊登单号,门店名称</param>
/// <param name="localFilePath">本地路径</param>
/// <param name="SheetName">工作表名称,例如:Ebay侵权下线</param>
/// <param name="message">错误信息</param>
public void ArrayToExcelTemplate(string[] columns, string localFilePath, string SheetName, ref string message)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
message = "无法创建Excel对象,可能计算机未安装Excel!";
return;
} //創建Excel對象
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
if (worksheet == null) worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(Type.Missing, Type.Missing, , Type.Missing);
Microsoft.Office.Interop.Excel.Range range = null; long totalCount = columns.Length;
worksheet.Name = SheetName;//第一个sheet在Excel中显示的名称
int c;
c = ;
////写入标题
for (int i = , count = columns.Length; i < count; i++)
{
//if (string.IsNullOrEmpty(columns[i])) continue;
worksheet.Cells[, c + ] = columns[i];
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, c + ];
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
c++; } try
{
localFilePath = Regex.Replace(localFilePath, ".xls$|.xlsx$", "", RegexOptions.IgnoreCase);
localFilePath += xlApp.Version.CompareTo("11.0") == ? ".xls" : ".xlsx";
workbook.SaveCopyAs(localFilePath);
}
catch (Exception ex)
{
message = "生成Excel附件过程中出现异常,详细信息如:" + ex.ToString();
} try
{
if (xlApp != null)
{ int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out lpdwProcessId);
System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
}
catch (Exception ex)
{
message = "Delete Excel Process Error:" + ex.Message;
} } /// <summary>
/// 导入Excel
/// </summary>
/// <param name="form"></param>
/// <param name="callback"></param>
public void ImportExcelToDataTable(Form form, Action<string, DataTable> callback, string SheetName = "Sheet1")
{
string Filter = "Excel文件|*.csv|Excel文件|*.xls|Excel文件|*.xlsx"; OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Excel文件";
openFileDialog1.Filter = Filter;
openFileDialog1.ValidateNames = true;
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true; if (openFileDialog1.ShowDialog() != DialogResult.OK)
return; var action = new Action(() =>
{
string localFilePath = openFileDialog1.FileName;
if (File.Exists(localFilePath))
{
string message = string.Empty;
string fileExten = Path.GetExtension(localFilePath); DataTable dtExcel;
if (fileExten.ToLower().Contains(".csv"))
{
dtExcel = ImportCSVFile(localFilePath, "Table1", ref message);
}
else
{
dtExcel = ImportExcelFile(localFilePath, "Table1", SheetName, ref message);
} if (callback != null)
{
if (form.InvokeRequired)
{
form.Invoke(callback, message, dtExcel);
}
else
{
callback(message, dtExcel);
}
}
}
}); action.BeginInvoke(null, null);
} /// <summary>
/// 执行导入
/// </summary>
/// <param name="strFileName">对应文件路径</param>
/// <param name="typeName">返回的Table名称</param>
/// <param name="message">返回的错误</param>
/// <returns>DataTable</returns>
public DataTable ImportCSVFile(string strFileName, string typeName, ref string message)
{
if (string.IsNullOrEmpty(strFileName)) return null; string line = string.Empty;
string[] split = null;
bool isReplace;
int subBegion;
int subEnd;
string itemString = string.Empty;
string oldItemString = string.Empty;
DataTable table = new DataTable(typeName);
DataRow row = null;
StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.Default);
//创建与数据源对应的数据列
line = sr.ReadLine();
split = line.Split(',');
foreach (String colname in split)
{
table.Columns.Add(colname, System.Type.GetType("System.String"));
}
//将数据填入数据表
int j = ;
while ((line = sr.ReadLine()) != null)
{
subEnd = ;
subBegion = ; if (line.IndexOf('\"') > )
{
isReplace = true;
}
else
{
isReplace = false;
}
itemString = string.Empty;
while (isReplace)
{ subBegion = line.IndexOf('\"');
subEnd = line.Length - ;
if (line.Length - > subBegion)
{
subEnd = line.IndexOf('\"', subBegion + );
} if (subEnd - subBegion > )
{
itemString = line.Substring(subBegion, subEnd - subBegion + );
oldItemString = itemString;
itemString = itemString.Replace(',', '|').Replace("\"", string.Empty);
line = line.Replace(oldItemString, itemString); } if (line.IndexOf('\"') == -)
{
isReplace = false;
} } j = ;
row = table.NewRow();
split = line.Split(',');
foreach (String colname in split)
{
row[j] = colname.Replace('|', ',');
j++;
}
table.Rows.Add(row);
}
sr.Close();
//显示数据 return table;
} /// <summary>
/// Excel执行导入
/// </summary>
/// <param name="strFileName">对应文件路径</param>
/// <param name="typeName">返回的Table名称</param>
/// <param name="message">返回的错误</param>
/// <returns></returns>
public DataTable ImportExcelFile(string strFileName, string typeName, string SheetName, ref string message)
{
if (string.IsNullOrEmpty(strFileName)) return null;
DataSet Exceldt;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
OleDbConnection con = new OleDbConnection();
try
{
//OleDbDataAdapter ExcelO = new OleDbDataAdapter(selectStr, @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFileName + ";Extended Properties=Excel 8.0;");
string ConnStr = xlApp.Version.CompareTo("11.0") == ? @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFileName + ";Extended Properties='Excel 8.0;IMEX=1;HDR=YES;'" : @"Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 8.0;IMEX=1;HDR=YES'; Data Source=" + strFileName;
con.ConnectionString = ConnStr;
con.Open();
DataTable dtOle = con.GetSchema("Tables");
DataTableReader dtReader = new DataTableReader(dtOle);
string TableName = "";
while (dtReader.Read())
{
TableName = dtReader["Table_Name"].ToString();
break;
}
OleDbDataAdapter excel = new OleDbDataAdapter(string.Format("select * from [" + SheetName + "$];", TableName), ConnStr);
//OleDbDataAdapter excel = new OleDbDataAdapter(selectStr, @"Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 8.0;IMEX=1;HDR=YES'; Data Source=" + strFileName); Exceldt = new DataSet();
excel.Fill(Exceldt, typeName);
return Exceldt.Tables.Count > ? Exceldt.Tables[] : null;
}
catch (OleDbException ex)
{
message = ex.Message;
return null;
}
catch (Exception ex)
{
message = ex.Message;
return null;
}
finally
{
con.Close();
}
}
}
}
4.演示代码
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 == )
{
MessageBox.Show("dt为空的");
return;
} if (dt.Rows.Count > )
{
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 = ;
foreach (var item in column1List)
{
if ((!decimal.TryParse(item, out isDecimal)) && !string.IsNullOrEmpty(item))
{
MessageBox.Show("列1必须是Decimal类型");
return;
}
if (isDecimal < )
{
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
}
}
5.演示
6.源代码下载
C#实现Excel模板导出和从Excel导入数据的更多相关文章
- java实现excel模板导出
一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...
- .Net NPOI 根据excel模板导出excel、直接生成excel
一.根据Excel模板导出excel 1.导入NPOI.dll 2.DAL中添加类ExportExcel.cs using NPOI.SS.UserModel; using System; usin ...
- ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据
ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...
- kettle 使用excel模板导出数据
通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...
- Magicodes.IE之Excel模板导出教材订购表
说明 本教程主要说明如果使用Magicodes.IE.Excel完成教材订购表的Excel模板导出. 要点 本教程使用Magicodes.IE.Excel来完成Excel模板导出 需要通过创建Dto来 ...
- Excel模板导出之动态导出
说明 目前Magicodes.IE已支持Excel模板导出时使用JObject.Dictionary和ExpandoObject来进行动态导出,具体使用请看本篇教程. 本功能的想法.部分实现初步源于a ...
- Net 自定义Excel模板导出数据
转载自:http://www.cnblogs.com/jbps/p/3549671.html?utm_source=tuicool&utm_medium=referral 1 using Sy ...
- 6、jeecg 笔记之 自定义excel 模板导出(一)
1.前言 jeecg 中已经自带 excel 的导出导出功能,其所使用的是 easypoi,尽管所导出的 excel 能满足大部分需求, 但总是有需要用到自定义 excel 导出模板,下文所用到的皆是 ...
- C# Winform Excel的导出,根据excel模板导出数据
namespace dxhbskymDemo { public partial class ExcelForm : DevExpress.XtraEditors.XtraForm { public E ...
随机推荐
- 原 JQuery监听页面滚动总结
1.当前滚动的地方的窗口顶端到整个页面顶端的距离: var winPos = $(window).scrollTop(); 2.获取指定元素的页面位置: $(val).offset().top; 3. ...
- bzoj2821: 作诗(Poetize)
分块 分sqrt(n)块 F[i][j]表示块i到块j的答案 s[i][j]表示数字i在前j块内出现了几次 #include <iostream> #include <cstdio& ...
- js,jquery转json的几种方法
一.原生js转json, eval()方法,不需要引入外部插件; //由JSON字符串转换为JSON对象 var obj = eval('(' + jsonStr + ')'); 或者 var obj ...
- 【bzoj3572】 世界树
http://www.lydsy.com/JudgeOnline/problem.php?id=3572 (题目链接) 题意 给出一棵n个节点的树,q次询问,每次给出k个关键点.规定对于树上每个节点归 ...
- cmd执行sql文件
string infile = @"C:\Users\yudm\Desktop\test\Patch.sql"; Process sqlprocess = new Process( ...
- Android成长日记-Fragment
(一)Android在3.0中引入了Fragment的概念,主要目的是用在大屏幕设备上—例如平板电脑上,支持更加动态和灵活的UI设计.平板电脑的屏幕要比手机大的多,有更多的空间放更多的UI组件,并且这 ...
- shell 调试手段总结
对于厌烦了的 print 和 echo,可以尝试点新鲜省力的小手段. 1. 使用 shell 的执行选项 sh 和 bash 常用的执行指令有:-n.-x.-c.-v. 其中: -n 是 noexec ...
- CentOS关闭火狐浏览器Flash过期提示
关闭旧版插件屏蔽提示 打开 about:config?filter=extensions.blocklist.enabled 右键切换,关闭flash版本过旧被屏蔽的提示. 参考: http://ti ...
- CF 702B Powers of Two(暴力)
题目链接: 传送门 Devu and Partitioning of the Array time limit per test:3 second memory limit per test: ...
- Alpha版本十天冲刺——Day 8
站立式会议 会议总结 队员 今天完成 遇到的问题 明天要做 感想 鲍亮 无 同时发送图片和其它字段信息(string)到服务器,找不到好方法实现 完成发帖接口 心累,写好了一个传送文件的接口,但是后端 ...