ExcelHelper.cs
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Data.OleDb;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection; namespace Comm
{
/// <summary>
/// Excel操作类
/// </summary>
/// Microsoft Excel 11.0 Object Library
public class ExcelHelper
{
#region 数据导出至Excel文件
/// </summary>
/// 导出Excel文件,自动返回可下载的文件流
/// </summary>
public static void DataTable1Excel(System.Data.DataTable dtData)
{
GridView gvExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
curContext.Response.Charset = "utf-8";
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
gvExport = new GridView();
gvExport.DataSource = dtData.DefaultView;
gvExport.AllowPaging = false;
gvExport.DataBind();
gvExport.RenderControl(htmlWriter);
curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString());
curContext.Response.End();
}
} /// <summary>
/// 导出Excel文件,转换为可读模式
/// </summary>
public static void DataTable2Excel(System.Data.DataTable dtData)
{
DataGrid dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null; if (dtData != null)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "";
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
} /// <summary>
/// 导出Excel文件,并自定义文件名
/// </summary>
public static void DataTable3Excel(System.Data.DataTable dtData, String FileName)
{
GridView dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null; if (dtData != null)
{
HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312";
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
} public static bool DataSetToExcel(DataSet dataSet, string fileName, bool isShowExcle)
{
DataTable dataTable = dataSet.Tables[0];
int rowNumber = dataTable.Rows.Count;
int columnNumber = dataTable.Columns.Count; if (rowNumber == 0)
{
//MessageBox.Show("没有任何数据可以导入到Excel文件!");
return false;
} //建立Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = excel.Application.Workbooks.Add(true);
excel.Visible = false;//是否打开该Excel文件 //填充数据
for (int i = 0; i < rowNumber; i++)
{
for (int j = 0; j < columnNumber; j++)
{
excel.Cells[i + 1, j + 1] = dataTable.Rows[i].ItemArray[j];
}
} //string fileName = path + "\\" + DateTime.Now.ToString().Replace(':', '_') + ".xls";
workBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); try
{
workBook.Saved = true;
excel.UserControl = false;
//excelapp.Quit();
}
catch (Exception exception)
{
//MessageBox.Show(exception.Message);
}
finally
{
workBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value);
excel.Quit();
} if (isShowExcle)
{
System.Diagnostics.Process.Start(fileName);
}
return true;
}
/// <summary>
/// 将数据导出至Excel文件
/// </summary>
/// <param name="Table">DataTable对象</param>
/// <param name="ExcelFilePath">Excel文件路径</param>
public static bool OutputToExcel(DataTable Table, string ExcelFilePath)
{
if (File.Exists(ExcelFilePath))
{
throw new Exception("该文件已经存在!");
} if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
{
Table.TableName = "Sheet1";
} //数据表的列数
int ColCount = Table.Columns.Count; //用于记数,实例化参数时的序号
int i = 0; //创建参数
OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的SQL语句
string TableStructStr = @"Create Table " + Table.TableName + "("; //连接字符串
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString); //创建表结构
OleDbCommand objCmd = new OleDbCommand(); //数据类型集合
ArrayList DataTypeList = new ArrayList();
DataTypeList.Add("System.Decimal");
DataTypeList.Add("System.Double");
DataTypeList.Add("System.Int16");
DataTypeList.Add("System.Int32");
DataTypeList.Add("System.Int64");
DataTypeList.Add("System.Single"); //遍历数据表的所有列,用于创建表结构
foreach (DataColumn col in Table.Columns)
{
//如果列属于数字列,则设置该列的数据类型为double
if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0)
{
para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double);
objCmd.Parameters.Add(para[i]); //如果是最后一列
if (i + 1 == ColCount)
{
TableStructStr += col.ColumnName + " double)";
}
else
{
TableStructStr += col.ColumnName + " double,";
}
}
else
{
para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar);
objCmd.Parameters.Add(para[i]); //如果是最后一列
if (i + 1 == ColCount)
{
TableStructStr += col.ColumnName + " varchar)";
}
else
{
TableStructStr += col.ColumnName + " varchar,";
}
}
i++;
} //创建Excel文件及文件结构
try
{
objCmd.Connection = objConn;
objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
} //插入记录的SQL语句
string InsertSql_1 = "Insert into " + Table.TableName + " (";
string InsertSql_2 = " Values (";
string InsertSql = ""; //遍历所有列,用于插入记录,在此创建插入记录的SQL语句
for (int colID = 0; colID < ColCount; colID++)
{
if (colID + 1 == ColCount) //最后一列
{
InsertSql_1 += Table.Columns[colID].ColumnName + ")";
InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")";
}
else
{
InsertSql_1 += Table.Columns[colID].ColumnName + ",";
InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ",";
}
} InsertSql = InsertSql_1 + InsertSql_2; //遍历数据表的所有数据行
for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
{
for (int colID = 0; colID < ColCount; colID++)
{
if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")
{
para[colID].Value = 0;
}
else
{
para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();
}
}
try
{
objCmd.CommandText = InsertSql;
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string str = exp.Message;
}
}
try
{
if (objConn.State == ConnectionState.Open)
{
objConn.Close();
}
}
catch (Exception exp)
{
throw exp;
}
return true;
} /// <summary>
/// 将数据导出至Excel文件
/// </summary>
/// <param name="Table">DataTable对象</param>
/// <param name="Columns">要导出的数据列集合</param>
/// <param name="ExcelFilePath">Excel文件路径</param>
public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath)
{
if (File.Exists(ExcelFilePath))
{
throw new Exception("该文件已经存在!");
} //如果数据列数大于表的列数,取数据表的所有列
if (Columns.Count > Table.Columns.Count)
{
for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++)
{
Columns.RemoveAt(s); //移除数据表列数后的所有列
}
} //遍历所有的数据列,如果有数据列的数据类型不是 DataColumn,则将它移除
DataColumn column = new DataColumn();
for (int j = 0; j < Columns.Count; j++)
{
try
{
column = (DataColumn)Columns[j];
}
catch (Exception)
{
Columns.RemoveAt(j);
}
}
if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
{
Table.TableName = "Sheet1";
} //数据表的列数
int ColCount = Columns.Count; //创建参数
OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的SQL语句
string TableStructStr = @"Create Table " + Table.TableName + "("; //连接字符串
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString); //创建表结构
OleDbCommand objCmd = new OleDbCommand(); //数据类型集合
ArrayList DataTypeList = new ArrayList();
DataTypeList.Add("System.Decimal");
DataTypeList.Add("System.Double");
DataTypeList.Add("System.Int16");
DataTypeList.Add("System.Int32");
DataTypeList.Add("System.Int64");
DataTypeList.Add("System.Single"); DataColumn col = new DataColumn(); //遍历数据表的所有列,用于创建表结构
for (int k = 0; k < ColCount; k++)
{
col = (DataColumn)Columns[k]; //列的数据类型是数字型
if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0)
{
para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double);
objCmd.Parameters.Add(para[k]); //如果是最后一列
if (k + 1 == ColCount)
{
TableStructStr += col.Caption.Trim() + " Double)";
}
else
{
TableStructStr += col.Caption.Trim() + " Double,";
}
}
else
{
para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar);
objCmd.Parameters.Add(para[k]); //如果是最后一列
if (k + 1 == ColCount)
{
TableStructStr += col.Caption.Trim() + " VarChar)";
}
else
{
TableStructStr += col.Caption.Trim() + " VarChar,";
}
}
} //创建Excel文件及文件结构
try
{
objCmd.Connection = objConn;
objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
} //插入记录的SQL语句
string InsertSql_1 = "Insert into " + Table.TableName + " (";
string InsertSql_2 = " Values (";
string InsertSql = ""; //遍历所有列,用于插入记录,在此创建插入记录的SQL语句
for (int colID = 0; colID < ColCount; colID++)
{
if (colID + 1 == ColCount) //最后一列
{
InsertSql_1 += Columns[colID].ToString().Trim() + ")";
InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")";
}
else
{
InsertSql_1 += Columns[colID].ToString().Trim() + ",";
InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ",";
}
} InsertSql = InsertSql_1 + InsertSql_2; //遍历数据表的所有数据行
DataColumn DataCol = new DataColumn();
for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
{
for (int colID = 0; colID < ColCount; colID++)
{
//因为列不连续,所以在取得单元格时不能用行列编号,列需得用列的名称
DataCol = (DataColumn)Columns[colID];
if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "")
{
para[colID].Value = 0;
}
else
{
para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim();
}
}
try
{
objCmd.CommandText = InsertSql;
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string str = exp.Message;
}
}
try
{
if (objConn.State == ConnectionState.Open)
{
objConn.Close();
}
}
catch (Exception exp)
{
throw exp;
}
return true;
}
#endregion
}
}
ExcelHelper.cs的更多相关文章
- 【干货分享】流程DEMO-采购预算编制
流程名: 采购预算编制 业务描述: 在月初由计财部进行预算编辑,提交审批后预算生效 流程相关文件: 流程包.xml WebService业务服务.xml WebService.asmx WebSe ...
- (C#)使用NPOI导出Excel
在做业务型的软件时,经常需要将某些数据导出,本文介绍了在Winform或Asp.net中使用NPOI(POI 项目的 .NET 版本)来操作Excel文件,而无需安装Office. 首先,需要获取NP ...
- C#实现Excel模板导出和从Excel导入数据
午休时间写了一个Demo关于Excel导入导出的简单练习 1.窗体 2.引用office命名空间 添加引用-程序集-扩展-Microsoft.Office.Interop.Excel 3.封装的Exc ...
- C#操作Excel数据增删改查(转)
C#操作Excel数据增删改查. 首先创建ExcelDB.xlsx文件,并添加两张工作表. 工作表1: UserInfo表,字段:UserId.UserName.Age.Address.CreateT ...
- C#操作Excel数据增删改查示例
Excel数据增删改查我们可以使用c#进行操作,首先创建ExcelDB.xlsx文件,并添加两张工作表,接下按照下面的操作步骤即可 C#操作Excel数据增删改查. 首先创建ExcelDB.xlsx文 ...
- NPOI的使用
简介:NPOI是POI(APATCH的一个开源项目)项目的.NET版本,最初的POI只用于JAVA来操作EXCEL or WORD等微软OLE2组件项目.使用NPOI可以完成在你没有安装Office或 ...
- asp.net(C#)之NPOI"操作Excel
1.首先到网上下载"NPOI.DLL".引用. 2.新建一个操作类"ExcelHelper.cs": using System.Collections.Gene ...
- SharePoint2013 Excel导出好的代码
C#Excel操作类ExcelHelper.cs 来源:http://www.hellocsharp.com/article/67.aspx C#源码世界 发布于: 2014-09-12 使用本类之前 ...
- 记React+.NetCore API实现动态列导出
1.效果演示 2.用到的第三方类库 前端:React,Dva,Antd 后端:ASP.NET CORE,System.Linq.Dynamic.Core,EPPlus.Core 3.基本思路 第一:E ...
随机推荐
- struts.xml 配置文件的主要元素
1.package元素 作用: 在struts2的配置文件中引入了面向对象思想.分包管理,易于管理动作类,便于模块化开发动作类. 属性: name:包的名称.名称唯一. extends:一般情况下需要 ...
- HDFS datanode心跳与运维中的实际案例
分布式系统的节点之间常采用心跳来维护节点的健康状态,如yarn的rm与nm之间,hdfs的nn与dn之间.DataNode会定期(dfs.heartbeat.interval配置项配置,默认是3秒)向 ...
- win 7 64 安装 MondgoDB 3.4
https://jingyan.baidu.com/article/f3e34a12ac10cef5eb653583.html mongod --dbpath "D:\Program Fil ...
- springCloud4---feign
JAX-WS : soap是遵循这个标准. JAX-RS : 标准,jersey框架遵循这个标准. Feign是一个声明式的web service客户端.Feign使用的负载均衡也是ribbon,Fe ...
- 20145321 《Java程序设计》第一周学习总结
20145321 <Java程序设计>第1周学习总结 教材学习内容总结 第一章 1.三大平台:Java SE.Java EE .Java ME 2.Java SE:由JVM.JRE.JDK ...
- 高手用的SourceInsight配置文件——仿Sublime风格【转】
本文转载自:https://blog.csdn.net/weixin_38233274/article/details/80209100 配置文件下载地址:https://download.csdn. ...
- vROPS中获取虚拟机在VC中的UUID
vROPS中虚拟机对象的ID为resourceID,跟vCenter中虚拟机的UUID是不一致的,因此想要将vROPS中的虚拟机和vCenter中的虚拟机对应肯定不能靠虚拟机名称,而是一定要靠UUID ...
- NOIP2015 T4 推销员 贪心+堆优化
前几天在学堆,这个数据结构貌似挺简单的,但是我看了很久啊QAQ... 今天算是搞懂了吧...于是想到了这道题...(当初悄悄咪咪看题解记得一点) 点我看题 放洛谷的题... 题意的话,大概就是有n个房 ...
- 代码审查工具Sonarqube安装
前言:在项目开发当中,完成需求并上线是一件很开心的事情,但为了能按时上线功能不得不为了完成功能而写代码,写的时候觉得先把功能上了以后再回头优化此处代码,但真正上线之后你就会发现你再也不想去修改之前遗留 ...
- Mysql(基础篇)
linux下的mysql操作 1.# 打开 MySQL 服务 sudo service mysql start 2.#使用 root 用户登录,密码为空 mysql -u root 3.创建数据库 C ...