午休时间写了一个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导入数据的更多相关文章

  1. java实现excel模板导出

    一. 准备工作 1. 点击此下载相关开发工具 2. 将poi-3.8.jxls-core-1.0两个jar包放到工程中,并引用 3. 将excel模板runRecord.xls放到RunRecordB ...

  2. .Net NPOI 根据excel模板导出excel、直接生成excel

    一.根据Excel模板导出excel 1.导入NPOI.dll  2.DAL中添加类ExportExcel.cs using NPOI.SS.UserModel; using System; usin ...

  3. 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的路由方案,与原来的方案在使用上差别不 ...

  4. kettle 使用excel模板导出数据

    通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...

  5. Magicodes.IE之Excel模板导出教材订购表

    说明 本教程主要说明如果使用Magicodes.IE.Excel完成教材订购表的Excel模板导出. 要点 本教程使用Magicodes.IE.Excel来完成Excel模板导出 需要通过创建Dto来 ...

  6. Excel模板导出之动态导出

    说明 目前Magicodes.IE已支持Excel模板导出时使用JObject.Dictionary和ExpandoObject来进行动态导出,具体使用请看本篇教程. 本功能的想法.部分实现初步源于a ...

  7. Net 自定义Excel模板导出数据

    转载自:http://www.cnblogs.com/jbps/p/3549671.html?utm_source=tuicool&utm_medium=referral 1 using Sy ...

  8. 6、jeecg 笔记之 自定义excel 模板导出(一)

    1.前言 jeecg 中已经自带 excel 的导出导出功能,其所使用的是 easypoi,尽管所导出的 excel 能满足大部分需求, 但总是有需要用到自定义 excel 导出模板,下文所用到的皆是 ...

  9. C# Winform Excel的导出,根据excel模板导出数据

    namespace dxhbskymDemo { public partial class ExcelForm : DevExpress.XtraEditors.XtraForm { public E ...

随机推荐

  1. 【POJ 2528】Mayor’s posters(线段树+离散化)

    题目 给定每张海报的覆盖区间,按顺序覆盖后,最后有几张海报没有被其他海报完全覆盖.离散化处理完区间端点,排序后再给相差大于1的相邻端点之间再加一个点,再排序.线段树,tree[i]表示节点i对应区间是 ...

  2. C++ 合成默认构造函数的真相

    对于C++默认构造函数,我曾经有两点误解: 类如果没有定义任何的构造函数,那么编译器(一定会!)将为类定义一个合成的默认构造函数. 合成默认构造函数会初始化类中所有的数据成员. 第一个误解来自于我学习 ...

  3. Hadoop2.x Permission denied: user=dr.who, access=READ_EXECUTE inode="/tmp"

    在hadoop2中查看网页中的/tmp目录出现下面的错误: Permission denied: user=dr.who, access=READ_EXECUTE inode="/tmp&q ...

  4. bzoj1113: [Poi2008]海报PLA

    #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...

  5. .net config文件 配置类的集合

    1,appconfig文件 <configSections> <section name="ToolConfig" type="DMTools.Tool ...

  6. UTF-8有签名和无签名的区别

    当有签名的UTF-8编码内容被解析器解析时,解析器直接根据签名即可判断出使用UTF-8编码来进行解析,当无签名时,解析器会根据内容的编码来进行判别.所以,有签名的将更容易被解析器以正确的编码方式进行解 ...

  7. AppVeyor-CI为GitHub项目做自动化集成(dotnet为主)

    travis-ci对dotnet的项目做自动化集成不太友好,尤其是使用mono的编译和不能使用MSTest进行自动化测试,所以转到appveyor进行. appveyor的配置非常简单,有两种方式: ...

  8. shell处理mysql增、删、改、查

    引言     这几天做一个任务,比对两个数据表中的数据,昨天用PHP写了一个版本,但考虑到有的机器没有php或者php没有编译mysql扩展,就无法使用mysql系列的函数,脚本就无效了,今天写个sh ...

  9. 通过Calendar类判断是否是周末及是否在指定时间

    package time; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; public cl ...

  10. Myeclipse 加载ojdbc14.jar步骤

    目的:加载驱动程序,需要找到驱动的具体位置,就是找到其驱动的类名,Class.forName("oracle.jdbc.driver.OracleDriver");//加载并注册驱 ...