excel c# 输出
引用:通过Com 引用 Microsoft Excel 5.0 对象程序库,引用后 bin 文件夹中会出现 Interop.Excel.dll ,Microsoft.Vbe.Interop.dll , Office.dll 三个文件。
//=====================ExcelHelper(套用模板输出Excel,并对数据进行分页)==============
using System;
using System.IO;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using cfg = System.Configuration;
using Excel;
namespace ExcelHelper
{
/// <summary>
/// 功能说明:套用模板输出Excel,并对数据进行分页
/// </summary>
public class ExcelHelper
{
protected string templetFile = null;
protected string outputFile = null;
protected object missing = Missing.Value;
/// <summary>
/// 构造函数,需指定模板文件和输出文件完整路径
/// </summary>
/// <param name="templetFilePath"> Excel模板文件路径 </param>
/// <param name="outputFilePath"> 输出Excel文件路径 </param>
public ExcelHelper(string templetFilePath, string outputFilePath)
{
if (templetFilePath == null)
throw new Exception(" Excel模板文件路径不能为空! ");
if (outputFilePath == null)
throw new Exception(" 输出Excel文件路径不能为空! ");
if (!File.Exists(templetFilePath))
throw new Exception(" 指定路径的Excel模板文件不存在! ");
this.templetFile = templetFilePath;
this.outputFile = outputFilePath;
}
/**/
/// <summary>
/// 将DataTable数据写入Excel文件(套用模板并分页)
/// </summary>
/// <param name="dt"> DataTable </param>
/// <param name="rows"> 每个WorkSheet写入多少行数据 </param>
/// <param name="top"> Excel中行索引 </param>
/// <param name="left"> Excel中列索引 </param>
/// <param name="sheetPrefixName"> WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2” </param>
public void DataTableToExcel(System.Data.DataTable dt, int rows, int top, int left, string sheetPrefixName)
{
int rowCount = dt.Rows.Count; // 源DataTable行数
int colCount = dt.Columns.Count; // 源DataTable列数
int sheetCount = this.GetSheetCount(rowCount, rows); // WorkSheet个数
DateTime beforeTime;
DateTime afterTime;
if (sheetPrefixName == null || sheetPrefixName.Trim() == "")
sheetPrefixName = " Sheet ";
// 创建一个Application对象并使其可见
beforeTime = DateTime.Now;
Excel.Application app = new Excel.ApplicationClass();
app.Visible = true;
afterTime = DateTime.Now;
// 打开模板文件,得到WorkBook对象 (网上都是13个参数,现在变成14个参数了)
Excel.Workbook workBook = app.Workbooks.Open(templetFile, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
// 得到WorkSheet对象
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
// 复制sheetCount-1个WorkSheet对象
for (int i = 1; i < sheetCount; i++)
{
((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing, workBook.Worksheets);
}
for (int i = 1; i <= sheetCount; i++)
{
int startRow = (i - 1) * rows; // 记录起始行索引
int endRow = i * rows; // 记录结束行索引
// 若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数
if (i == sheetCount)
endRow = rowCount;
// 获取要写入数据的WorkSheet对象,并重命名
Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
sheet.Name = sheetPrefixName + " - " + i.ToString();
// 将dt中的数据写入WorkSheet
for (int j = 0; j < endRow - startRow; j++)
{
for (int k = 0; k < colCount; k++)
{
sheet.Cells[top + j, left + k] = dt.Rows[startRow + j][k].ToString();
}
}
====================写文本框数据(有错误注释掉了)=============
//Excel.TextBox txtAuthor = (Excel.TextBox)sheet.TextBoxes(" txtAuthor ");
//Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes(" txtDate ");
//Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes(" txtVersion ");
//txtAuthor.Text = " KLY.NET的Blog ";
//txtDate.Text = DateTime.Now.ToShortDateString();
//txtVersion.Text = " 1.0.0.0 ";
sheet.Cells[rows + 1, left + 1] = "总计:10000";
sheet.Cells[rows + 1, left + 5] = "编码:10000";
}
// 输出Excel文件并退出
try
{
//(网上是11个参数,现在是12个参数)
workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
workSheet = null;
workBook = null;
app = null;
GC.Collect();
}
catch (Exception e)
{
throw e;
}
finally
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName(" Excel ");
// 得不到Excel进程ID,暂时只能判断进程启动时间
foreach (Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
}
}
}
}
/**/
/// <summary>
/// 获取WorkSheet数量
/// </summary>
/// <param name="rowCount"> 记录总行数 </param>
/// <param name="rows"> 每WorkSheet行数 </param>
private int GetSheetCount(int rowCount, int rows)
{
int n = rowCount % rows; // 余数
if (n == 0)
return rowCount / rows;
else
return Convert.ToInt32(rowCount / rows) + 1;
}
}
}
使用示例:
public partial class _Default : System.Web.UI.Page
{
ExcelHelper.ExcelHelper excel =null;
protected void Page_Load(object sender, EventArgs e)
{
excel = new ExcelHelper.ExcelHelper(Server.MapPath("tempt/BJStock.xls"), Server.MapPath("ExcelFile/test.xls"));
}
protected void Button1_Click(object sender, EventArgs e)
{
excel.DataTableToExcel(DbHelperSQL.DbHelperSQL.GetDataTable("select * from excel"), 2, 1, 1, "Sheet");
Response.Redirect("ExcelFile/test.xls");
}
}
附件
excel c# 输出相关推荐
- EXCEL描述统计输出详解:标准误、置信度、偏度、峰度和JB检验
本文介绍EXCEL描述统计输出的各个细节,主要围绕标准差相关指标展开.包括: 解释标准差.标准误差.置信度之间的关系 介绍各指标在EXCEL中如何单独计算 介绍各指标的统计学公式 重点强调一下峰度和偏 ...
- 基于Jupyter 完成聚类输出可视化效果+Excel数据处理输出分布饼图
基于Jupyter 完成聚类输出可视化效果+Excel数据处理输出分布饼图 一.根据计科18大类学生的成绩数据(选取两个特征:1.平均成绩GPA: 2.面向对象程序设计成绩),将计科18大类学生分成 ...
- vba 输出文本 m Linux,利用VBA实现EXCEL数据输出TXT等文本文件
VBA--Visual Basic For Application的简称,属于VB的一个子集,广泛应用于Word套件的自动化,其寄存于现有的EXCEL或word等的文件里面 日常生活中,需要做到有逻辑 ...
- php 导出多个excel并输出压缩文件
set_time_limit(0);ob_end_clean();header('Content-Encoding: none');header('Content-Type: application/ ...
- kettle EXCEL 累计输出数据
项目当中有些数据是需要进行累积的,每次读取原有数据再写入全部数据,耗时太多. 以前输出excel 都是直接选择 kettle 当中的 Excel输出,然而今天眼前一亮. Excel输出 输出的exc ...
- Excel如何输出高清图片?
在Excel作图完成后,很多时候需要保存后在其他地方使用,大部分人选择截图,虽然很方便,但是不清晰.按照下面的方法,可以输出高清的图片. 01)选中想输出的图片,点击Excel右上角复,单击复制为图片 ...
- Java Poi 在Excel中输出特殊符号
最近的工作围绕报表导出,并没有集成相应的报表插件,只是使用了Poi.其中有一个需求,Excel中导出特殊符号,如√.×等.在网上找寻了许久,没有相关资料,故记录分享一下. 思考良久,走了不少弯路,最后 ...
- java显示excel_怎样实现把java显示的结果在EXCEL中输出
展开全部 1./** * 出险信息导出到excel(fc) * @param mapping * @param form * @param request * @param response * @t ...
- struts1 使用poi组件 读取excel文件,创建excel ,输出excel文件
首先要下载poi.jar 包,还有上传文件的包:commons.fileupload.jar.commons.logging.jar.commons.beanutils.jar.commons.col ...
最新文章
- 《Java编程思想》第四版读书笔记 第十四章 类型信息
- 奖客富翁系统python_作业 2018-12-28 20.1 奖客富翁
- 部分视图传viewbag_无法在ASP.NET MVC3的部分视图中访问ViewBag
- 基于Dubbo框架构建分布式服务(三)
- The table(CF226D)
- 微型计算机和接口技术考题,微型计算机接口技术以及应用考题
- mybatis防止sql注入
- cairo在Gecko上实现的路线图
- 超大背包问题(折半枚举, 双向搜索)
- python爬取汽车之家数据_Python神技能 | 使用爬虫获取汽车之家全车型数据
- 原码一位乘的数值运算
- 怎样才能够修改PDF文件中的文字大小
- linux环境下的jmeter测试
- 【生信】全基因组测序(WGS)
- 2020你必须掌握的CSS特效~建议收藏
- [绍棠] iOS视频播放AVPlayer的视频内容拉伸设置
- acml会议级别_人工智能领域的顶级学术会议大全(二)
- golang lint
- mysql的时区设置
- Android支付接入(一):支付宝
热门文章
- C++语言基础 —— STL —— 算法 —— unique() 的使用
- 排队接水(信息学奥赛一本通-T1319)
- 58 SD配置-科目分配-定义科目代码
- 8 MM配置-主数据-定义行业部门和具体行业部门字段选择
- 一起学习C语言:C语言基本语法(一)
- 多级队列调度算法可视化界面_进程调度功能由操作系统内核的进程调度程序完成...
- Windows手动更新补丁
- K8S集群安装KubeSphere失败记录
- 一个可以下载Github指定子文件夹的Chrome插件
- gvim 配置_Python与开源GIS教程:1.3. 配置Python开源GIS环境