一:C#导入导出EXCEL文件的类

代码如下:

首先将Microsoft Excel 14.0 Object Library 引用导入

using System;
using System.Data;
using System.Data.OleDb; namespace ZFSoft.Joint
{
public class ExcelIO
{
private int _ReturnStatus;
private string _ReturnMessage; /// <summary>
/// 执行返回状态
/// </summary>
public int ReturnStatus
{
get
{
return _ReturnStatus;
}
} /// <summary>
/// 执行返回信息
/// </summary>
public string ReturnMessage
{
get
{
return _ReturnMessage;
}
} public ExcelIO()
{
} /// <summary>
/// 导入EXCEL到DataSet
/// </summary>
/// <param name="fileName">Excel全路径文件名</param>
/// <returns>导入成功的DataSet</returns>
public DataTable ImportExcel(string fileName)
{
//判断是否安装EXCEL
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
_ReturnStatus = -;
_ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
return null;
} //判断文件是否被其他进程使用
Microsoft.Office.Interop.Excel.Workbook workbook;
try
{
workbook = xlApp.Workbooks.Open(fileName, , false, , "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, , true, , );
}
catch
{
_ReturnStatus = -;
_ReturnMessage = "Excel文件处于打开状态,请保存关闭";
return null;
} //获得所有Sheet名称
int n = workbook.Worksheets.Count;
string[] SheetSet = new string[n];
System.Collections.ArrayList al = new System.Collections.ArrayList();
for (int i = ; i <= n; i++)
{
SheetSet[i - ] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i]).Name;
} //释放Excel相关对象
workbook.Close(null, null, null);
xlApp.Quit();
if (workbook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
GC.Collect(); //把EXCEL导入到DataSet
DataSet ds = new DataSet();
DataTable table = new DataTable();
string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + fileName + ";Extended Properties=Excel 8.0";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter da;
string sql = "select * from [" + SheetSet[] + "$] ";
da = new OleDbDataAdapter(sql, conn);
da.Fill(ds, SheetSet[]);
da.Dispose();
table = ds.Tables[];
conn.Close();
conn.Dispose();
}
return table;
} /// <summary>
/// 把DataTable导出到EXCEL
/// </summary>
/// <param name="reportName">报表名称</param>
/// <param name="dt">数据源表</param>
/// <param name="saveFileName">Excel全路径文件名</param>
/// <returns>导出是否成功</returns>
public bool ExportExcel(string reportName, System.Data.DataTable dt, string saveFileName)
{
if (dt == null)
{
_ReturnStatus = -;
_ReturnMessage = "数据集为空!";
return false;
} bool fileSaved = false;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
_ReturnStatus = -;
_ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
return false;
} 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 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];//取得sheet1
worksheet.Cells.Font.Size = ;
Microsoft.Office.Interop.Excel.Range range; long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ; worksheet.Cells[, ] = reportName;
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, ]).Font.Size = ;
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, ]).Font.Bold = true; //写入字段
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ];
range.Interior.ColorIndex = ;
range.Font.Bold = true; }
//写入数值
for (int r = ; r < dt.Rows.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + , i + ] = dt.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)( * rowRead)) / totalCount;
}
//此行有可能会出错,解决办法见下面
range = worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[dt.Rows.Count + , dt.Columns.Count]);
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
if (dt.Rows.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
}
if (dt.Columns.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
} //保存文件
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
_ReturnStatus = -;
_ReturnMessage = "导出文件时出错,文件可能正被打开!\n" + ex.Message;
}
}
else
{
fileSaved = false;
} //释放Excel对应的对象
if (range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if (worksheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
}
if (workbook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (workbooks != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
workbooks = null;
}
xlApp.Application.Workbooks.Close();
xlApp.Quit();
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
GC.Collect();
return fileSaved;
}
}
}

这种写法可能出现,Object未包含get_range定义,解决办法是将get_range变为Range:

range = worksheet.Range[worksheet.Cells[, ], worksheet.Cells[dt.Rows.Count + , dt.Columns.Count]];

调用该类的具体使用,导入表中的数据到dataGridView,实际上也是先到dataset里面:

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Excel Files|*.xlsx"; if (ofd.ShowDialog() == DialogResult.OK)
{ string filename = ofd.FileName;
ExcelIO ex = new ExcelIO();
dataGridView1.DataSource = ex.ImportExcel(filename); }
}

调用该类的具体使用,从数据库导出到Excel,实际上也是先到dataset里面:

 private void button2_Click(object sender, EventArgs e)
{
CarTableAdapter ca = new CarTableAdapter();
DataSet1.CarDataTable table = ca.GetData(); ExcelIO ex = new ExcelIO();
ex.ExportExcel("qiche",table,@"C:\Users\Administrator\Desktop\例子.xlsx"); }

二:C# WinForm导出Excel方法

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,.NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢;如下代码所示已经做了优化,将一个二维对象数组赋值到一个单元格区域中(下面的代码中只能用于导出列数不多于26列的数据导出):

OFFICE PIA:

public static void ExportToExcel(DataSet dataSet, string outputPath)
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
int sheetIndex = ;
foreach (System.Data.DataTable dt in dataSet.Tables)
{
object[,] data = new object[dt.Rows.Count + , dt.Columns.Count];
for (int j = ; j < dt.Columns.Count; j++)
{
data[, j] = dt.Columns[j].ColumnName;
}
for (int j = ; j < dt.Columns.Count; j++)
{
for (int i = ; i < dt.Rows.Count; i++)
{
data[i + , j] = dt.Rows[i][j];
}
}
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(dt.Columns.Count - ) / colCharsetLen - , );
}
finalColLetter += colCharset.Substring(
(dt.Columns.Count - ) % colCharsetLen, ); Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets.Add(
workbook.Sheets.get_Item(++sheetIndex),
Type.Missing, , Excel.XlSheetType.xlWorksheet);
sheet.Name = dt.TableName;
string range = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + );
sheet.get_Range(range, Type.Missing).Value2 = data;
((Excel.Range)sheet.Rows[, Type.Missing]).Font.Bold = true;
}
workbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
excel.Quit();
KillSpecialExcel(excel);
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
static void KillSpecialExcel(Excel.Application app)
{
try
{
if (app != null)
{
int processId;
GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId);
System.Diagnostics.Process.GetProcessById(processId).Kill();
}
}
catch (Exception ex)
{
throw ex;
}
}

文件流

这种方法的效率明显高于第一种,而且也不需要安装Office,但是导出的xls文件并不符合Excel的格式标准,在打开生成的xls文件时会提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.

public static void ExportToExcel(System.Data.DataSet ds, string path)
{
StreamWriter sw = null;
try
{
long totalCount = ds.Tables[].Rows.Count;
sw = new StreamWriter(path, false, Encoding.Unicode);
StringBuilder sb = new StringBuilder();
for (int i = ; i < ds.Tables[].Columns.Count; i++)
{
sb.Append(ds.Tables[].Columns[i].ColumnName + "\t");
}
sb.Append(Environment.NewLine);
for (int i = ; i < ds.Tables[].Rows.Count; i++)
{
for (int j = ; j < ds.Tables[].Columns.Count; j++)
{
sb.Append(ds.Tables[].Rows[i][j].ToString() + "\t");
}
sb.Append(Environment.NewLine);
}
sw.Write(sb.ToString());
sw.Flush();
}
catch (IOException ioe)
{
throw ioe;
}
finally
{
if (sw != null)
{
sw.Close();
}
}
}

三:WinForm项目开发中Excel用法实例解析

在实际项目的开发过程中,所涉及的EXCEL往往会比较复杂,并且列中还会带有一些计算公式,这就给读取带来了很大的困难,曾经尝试过一些免费的第三方dll,譬如Myxls,NPOI,IExcelDataReader都会出现一些问题,最后采用OLEDB形式读取,再x64操作系统上有点问题,不过采用小技巧即可解决。

namespace DBUtilHelpV2
{
public class OLEDBExcelToolV2
{
static readonly string xls = ".xls";
static readonly string xlsx = ".xlsx";
string _ExcelExtension = string.Empty;//后缀
string _ExcelPath = string.Empty;//路径
string _ExcelConnectString = string.Empty;//链接字符串
static bool _X64Version = false;//是否强制使用x64链接字符串,即xlsx形式
public OLEDBExcelToolV2(string excelPath, bool x64Version)
{
if (string.IsNullOrEmpty(excelPath))
throw new ArgumentNullException("excelPath");
if (!File.Exists(excelPath))
throw new ArgumentException("excelPath");
string _excelExtension = Path.GetExtension(excelPath);
_ExcelExtension = _excelExtension.ToLower();
_ExcelPath = excelPath;
_X64Version = x64Version;
_ExcelConnectString = BuilderConnectionString();
}
/// <summary>
/// 创建链接字符串
/// </summary>
/// <returns></returns>
private string BuilderConnectionString()
{
Dictionary<string, string> _connectionParameter = new Dictionary<string, string>();
if (!_ExcelExtension.Equals(xlsx) && !_ExcelExtension.Equals(xls))
{
throw new ArgumentException("excelPath");
} if (!_X64Version)
{
if (_ExcelExtension.Equals(xlsx))
{
// XLSX - Excel 2007, 2010, 2012, 2013
_connectionParameter["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
_connectionParameter["Extended Properties"] = "'Excel 12.0 XML;IMEX=1'";
}
else if (_ExcelExtension.Equals(xls))
{
// XLS - Excel 2003 and Older
_connectionParameter["Provider"] = "Microsoft.Jet.OLEDB.4.0";
_connectionParameter["Extended Properties"] = "'Excel 8.0;IMEX=1'";
}
}
else
{
_connectionParameter["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
_connectionParameter["Extended Properties"] = "'Excel 12.0 XML;IMEX=1'";
} _connectionParameter["Data Source"] = _ExcelPath;
StringBuilder _connectionString = new StringBuilder(); foreach (KeyValuePair<string, string> parameter in _connectionParameter)
{
_connectionString.Append(parameter.Key);
_connectionString.Append('=');
_connectionString.Append(parameter.Value);
_connectionString.Append(';');
}
return _connectionString.ToString();
}
/// <summary>
/// Excel操作
/// DELETE不支持
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteNonQuery(string sql)
{
int _affectedRows = -;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
using (OleDbCommand sqlcmd = new OleDbCommand(sql, sqlcon))
{
_affectedRows = sqlcmd.ExecuteNonQuery();
}
}
catch (Exception)
{
return -;
}
}
return _affectedRows;
}
/// <summary>
/// Excel操作
///获取EXCEL内sheet集合
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public string[] GetExcelSheetNames()
{
DataTable _schemaTable = null;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
_schemaTable = sqlcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] _excelSheets = new String[_schemaTable.Rows.Count];
int i = ;
foreach (DataRow row in _schemaTable.Rows)
{
_excelSheets[i] = row["TABLE_NAME"].ToString().Trim();
i++;
}
return _excelSheets;
}
catch (Exception)
{
return null;
}
finally
{
if (_schemaTable != null)
{
_schemaTable.Dispose();
}
}
}
}
/// <summary>
/// 读取sheet
/// eg:select * from [Sheet1$]
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable ExecuteDataTable(string sql)
{
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
using (OleDbCommand sqlcmd = new OleDbCommand(sql, sqlcon))
{
using (OleDbDataAdapter sqldap = new OleDbDataAdapter(sqlcmd))
{
DataTable _dtResult = new DataTable();
sqldap.Fill(_dtResult);
return _dtResult;
}
}
}
catch (Exception)
{
return null;
}
} }
/// <summary>
/// 获取excel所有sheet数据
/// </summary>
/// <returns>DataSet</returns>
public DataSet ExecuteDataSet()
{
DataSet _excelDb = null;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
DataTable _schemaTable = sqlcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (_schemaTable != null)
{
int i = ;
_excelDb = new DataSet();
foreach (DataRow row in _schemaTable.Rows)
{
string _sheetName = row["TABLE_NAME"].ToString().Trim();
string _sql = string.Format("select * from [{0}]", _sheetName);
using (OleDbCommand sqlcmd = new OleDbCommand(_sql, sqlcon))
{
using (OleDbDataAdapter sqldap = new OleDbDataAdapter(sqlcmd))
{
DataTable _dtResult = new DataTable();
_dtResult.TableName = _sheetName;
sqldap.Fill(_dtResult);
_excelDb.Tables.Add(_dtResult);
}
}
i++;
}
}
}
catch (Exception)
{
return null;
}
}
return _excelDb;
}
}
}

代码使用方法:

/// <summary>
/// 合并EXCEL数据
/// </summary>
/// <param name="_excelPath">excel路径</param>
private void HandleMergeExcel(string _excelPath)
{
if (!string.IsNullOrEmpty(_excelPath))
{
OLEDBExcelToolV2 _excelHelper = new OLEDBExcelToolV2(_excelPath, true);
DataSet _excelSource = _excelHelper.ExecuteDataSet();
HandleExcelSource(_excelSource);
}
}

若在x64操作系统,将第二个参数设置true,并且按照AccessDatabaseEngine_X64.exe即可正常读取。

C#导入导出Excel表的数据的更多相关文章

  1. thinkphp导入导出excel表单数据

    在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传e ...

  2. Java利用POI导入导出Excel中的数据

         首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...

  3. 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...

  4. winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

    1.通过NUGET管理器下载nopi,在引入命令空间 using System; using System.Collections.Generic; using System.Text; using ...

  5. c# 导入导出excel表格式

    c#使用代码导入excel时,当遇到纯数字且大于15位时会出现编码混乱(表现为科学计数法),要想呈现与excel表中纯数字格式和在数据库中呈现纯数字,操作如下: 完成即可. 导出取决于导入的内容排版.

  6. 【ITOO 1】将List数据导出Excel表

    需求描述:在课表导入的时候,首先给用户提供模板(excel),然后将用户填写好的数据读取到list集合中.再进行判空处赋值处理,以及去重处理.这篇博客,主要介绍读取excel表和导出excel表的方法 ...

  7. C#中缓存的使用 ajax请求基于restFul的WebApi(post、get、delete、put) 让 .NET 更方便的导入导出 Excel .net core api +swagger(一个简单的入门demo 使用codefirst+mysql) C# 位运算详解 c# 交错数组 c# 数组协变 C# 添加Excel表单控件(Form Controls) C#串口通信程序

    C#中缓存的使用   缓存的概念及优缺点在这里就不多做介绍,主要介绍一下使用的方法. 1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可:  <%@ Outp ...

  8. 关于导出Excel表中存在部门或用户数据权限问题

    /** * 导出Controller */ @RequiresPermissions("xxx:weeklightlimit:download") @RequestMapping( ...

  9. NPOI导入导出Excel数据

    代码: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; usi ...

随机推荐

  1. 内省与JavaBean

    概述 JavaBean代表一类特殊的Java类,这种类主要用来存储和传递属性信息,JavaBean中的方法主要用于设置和获取这些私有属性,他们有一定的命名规则,我们可以把它们想象为一个侧重属性信息的类 ...

  2. NOIP2014 无线网络发射器选址

    1.无线网络发射器选址 (wireless.cpp/c/pas) [问题描述] 随着智能手机的日益普及,人们对无线网的需求日益增大.某城市决定对城市内的公共场所覆盖无线网. 假设该城市的布局为由严格平 ...

  3. Yum本地源配置

    1.mount -t auto /dev/cdrom /mnt      使用光驱 mount -t iso9660 -o loop /home/software/rhel-server-6.4-x8 ...

  4. Android之指南针(电子罗盘)学习

    点我下载源码 5月12日更新到V5版:http://download.csdn.net/detail/weidi1989/5364243 今天,在小米的开源项目中下载了一个指南针源码学习了一下,感觉不 ...

  5. Java & XML Tutorial

    Java comes with a set of tools to process XML. These Java XML tools are: SAX Parser StAX Parser DOM ...

  6. kvo原理概述

    kvo概述 kvo,全称Key-Value Observing,它提供了一种方法,当对象某个属性发生改变时,允许监听该属性值变化的对象可以接受到通知,然后通过kvo的方法响应一些操作. kvo实现原理 ...

  7. 推荐《C Primer Plus(第五版)中文版》【worldsing笔记】

      老外写的C书,看了你会有一种哇塞的感觉,这里提供PDF扫描版的下在,包含数内的例程,请大家支持原版!! C Primer Plus(第五版)中文版.pdf  下载地址:http://pan.bai ...

  8. gmt学习资源

    1 http://seisman.info/ http://examples.gmt-china.org/ http://docs.gmt-china.org http://modules.gmt-c ...

  9. iOS 定时器Timer常见问题

    最近有朋友问我使用NStimer遇见与ScrollView并存时存在主线程阻塞的问题,自己总结几种解决方法: 问题原因: 一般定时器timer都会被以默认模式default添加到主线程的runloop ...

  10. HBase 使用场景和成功案例

    有时候了解软件产品的最好方法是看看它是怎么用的.它可以解决什么问题和这些解决方案如何适用于大型应用架构,能够告诉你很多.因为HBase有许多公开的产品部署,我们正好可以这么做.本章节将详细介绍一些人们 ...