点击下载 DataToExcel.rar

看下面代码吧

/// <summary>
/// 类说明:DataToExcel
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.Diagnostics;
//using Excel;
namespace DotNet.Utilities
{
/// <summary>
/// 操作EXCEL导出数据报表的类
/// </summary>
public class DataToExcel
{
public DataToExcel()
{
} #region 操作EXCEL的一个类(需要Excel.dll支持) private int titleColorindex = ;
/// <summary>
/// 标题背景色
/// </summary>
public int TitleColorIndex
{
set { titleColorindex = value; }
get { return titleColorindex; }
} private DateTime beforeTime; //Excel启动之前时间
private DateTime afterTime; //Excel启动之后时间 #region 创建一个Excel示例
/// <summary>
/// 创建一个Excel示例
/// </summary>
public void CreateExcel()
{
//Excel.Application excel = new Excel.Application();
//excel.Application.Workbooks.Add(true);
//excel.Cells[1, 1] = "第1行第1列";
//excel.Cells[1, 2] = "第1行第2列";
//excel.Cells[2, 1] = "第2行第1列";
//excel.Cells[2, 2] = "第2行第2列";
//excel.Cells[3, 1] = "第3行第1列";
//excel.Cells[3, 2] = "第3行第2列"; ////保存
//excel.ActiveWorkbook.SaveAs("./tt.xls", XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
////打开显示
//excel.Visible = true;
//// excel.Quit();
//// excel=null;
//// GC.Collect();//垃圾回收
}
#endregion #region 将DataTable的数据导出显示为报表
/// <summary>
/// 将DataTable的数据导出显示为报表
/// </summary>
/// <param name="dt">要导出的数据</param>
/// <param name="strTitle">导出报表的标题</param>
/// <param name="FilePath">保存文件的路径</param>
/// <returns></returns>
//public string OutputExcel(System.Data.DataTable dt, string strTitle, string FilePath)
//{
// beforeTime = DateTime.Now; // Excel.Application excel;
// Excel._Workbook xBk;
// Excel._Worksheet xSt; // int rowIndex = 4;
// int colIndex = 1; // excel = new Excel.ApplicationClass();
// xBk = excel.Workbooks.Add(true);
// xSt = (Excel._Worksheet)xBk.ActiveSheet; // //取得列标题
// foreach (DataColumn col in dt.Columns)
// {
// colIndex++;
// excel.Cells[4, colIndex] = col.ColumnName; // //设置标题格式为居中对齐
// xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Font.Bold = true;
// xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
// xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Select();
// xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Interior.ColorIndex = titleColorindex;//19;//设置为浅黄色,共计有56种
// } // //取得表格中的数据
// foreach (DataRow row in dt.Rows)
// {
// rowIndex++;
// colIndex = 1;
// foreach (DataColumn col in dt.Columns)
// {
// colIndex++;
// if (col.DataType == System.Type.GetType("System.DateTime"))
// {
// excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
// xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
// }
// else
// if (col.DataType == System.Type.GetType("System.String"))
// {
// excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
// xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
// }
// else
// {
// excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
// }
// }
// } // //加载一个合计行
// int rowSum = rowIndex + 1;
// int colSum = 2;
// excel.Cells[rowSum, 2] = "合计";
// xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
// //设置选中的部分的颜色
// xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Select();
// //xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex =Assistant.GetConfigInt("ColorIndex");// 1;//设置为浅黄色,共计有56种 // //取得整个报表的标题
// excel.Cells[2, 2] = strTitle; // //设置整个报表的标题格式
// xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Bold = true;
// xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Size = 22; // //设置报表表格为最适应宽度
// xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Select();
// xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Columns.AutoFit(); // //设置整个报表的标题为跨列居中
// xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).Select();
// xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection; // //绘制边框
// xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1;
// xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, 2]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThick;//设置左边线加粗
// xSt.get_Range(excel.Cells[4, 2], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlThick;//设置上边线加粗
// xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThick;//设置右边线加粗
// xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThick;//设置下边线加粗 // afterTime = DateTime.Now; // //显示效果
// //excel.Visible=true;
// //excel.Sheets[0] = "sss"; // ClearFile(FilePath);
// string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
// excel.ActiveWorkbook.SaveAs(FilePath + filename, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); // //wkbNew.SaveAs strBookName;
// //excel.Save(strExcelFileName); // #region 结束Excel进程 // //需要对Excel的DCOM对象进行配置:dcomcnfg // //excel.Quit();
// //excel=null; // xBk.Close(null, null, null);
// excel.Workbooks.Close();
// excel.Quit(); // //注意:这里用到的所有Excel对象都要执行这个操作,否则结束不了Excel进程
// // if(rng != null)
// // {
// // System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
// // rng = null;
// // }
// // if(tb != null)
// // {
// // System.Runtime.InteropServices.Marshal.ReleaseComObject(tb);
// // tb = null;
// // }
// if (xSt != null)
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
// xSt = null;
// }
// if (xBk != null)
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
// xBk = null;
// }
// if (excel != null)
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
// excel = null;
// }
// GC.Collect();//垃圾回收
// #endregion // return filename; //}
#endregion #region Kill Excel进程 /// <summary>
/// 结束Excel进程
/// </summary>
public void KillExcelProcess()
{
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();
}
}
}
#endregion #endregion #region 将DataTable的数据导出显示为报表(不使用Excel对象,使用COM.Excel) #region 使用示例
/*使用示例:
* DataSet ds=(DataSet)Session["AdBrowseHitDayList"];
string ExcelFolder=Assistant.GetConfigString("ExcelFolder");
string FilePath=Server.MapPath(".")+"\\"+ExcelFolder+"\\"; //生成列的中文对应表
Hashtable nameList = new Hashtable();
nameList.Add("ADID", "广告编码");
nameList.Add("ADName", "广告名称");
nameList.Add("year", "年");
nameList.Add("month", "月");
nameList.Add("browsum", "显示数");
nameList.Add("hitsum", "点击数");
nameList.Add("BrowsinglIP", "独立IP显示");
nameList.Add("HitsinglIP", "独立IP点击");
//利用excel对象
DataToExcel dte=new DataToExcel();
string filename="";
try
{
if(ds.Tables[0].Rows.Count>0)
{
filename=dte.DataExcel(ds.Tables[0],"标题",FilePath,nameList);
}
}
catch
{
//dte.KillExcelProcess();
} if(filename!="")
{
Response.Redirect(ExcelFolder+"\\"+filename,true);
}
*
* */ #endregion /// <summary>
/// 将DataTable的数据导出显示为报表(不使用Excel对象)
/// </summary>
/// <param name="dt">数据DataTable</param>
/// <param name="strTitle">标题</param>
/// <param name="FilePath">生成文件的路径</param>
/// <param name="nameList"></param>
/// <returns></returns>
//public string DataExcel(System.Data.DataTable dt, string strTitle, string FilePath, Hashtable nameList)
//{
// COM.Excel.cExcelFile excel = new COM.Excel.cExcelFile();
// ClearFile(FilePath);
// string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
// excel.CreateFile(FilePath + filename);
// excel.PrintGridLines = false; // COM.Excel.cExcelFile.MarginTypes mt1 = COM.Excel.cExcelFile.MarginTypes.xlsTopMargin;
// COM.Excel.cExcelFile.MarginTypes mt2 = COM.Excel.cExcelFile.MarginTypes.xlsLeftMargin;
// COM.Excel.cExcelFile.MarginTypes mt3 = COM.Excel.cExcelFile.MarginTypes.xlsRightMargin;
// COM.Excel.cExcelFile.MarginTypes mt4 = COM.Excel.cExcelFile.MarginTypes.xlsBottomMargin; // double height = 1.5;
// excel.SetMargin(ref mt1, ref height);
// excel.SetMargin(ref mt2, ref height);
// excel.SetMargin(ref mt3, ref height);
// excel.SetMargin(ref mt4, ref height); // COM.Excel.cExcelFile.FontFormatting ff = COM.Excel.cExcelFile.FontFormatting.xlsNoFormat;
// string font = "宋体";
// short fontsize = 9;
// excel.SetFont(ref font, ref fontsize, ref ff); // byte b1 = 1,
// b2 = 12;
// short s3 = 12;
// excel.SetColumnWidth(ref b1, ref b2, ref s3); // string header = "页眉";
// string footer = "页脚";
// excel.SetHeader(ref header);
// excel.SetFooter(ref footer); // COM.Excel.cExcelFile.ValueTypes vt = COM.Excel.cExcelFile.ValueTypes.xlsText;
// COM.Excel.cExcelFile.CellFont cf = COM.Excel.cExcelFile.CellFont.xlsFont0;
// COM.Excel.cExcelFile.CellAlignment ca = COM.Excel.cExcelFile.CellAlignment.xlsCentreAlign;
// COM.Excel.cExcelFile.CellHiddenLocked chl = COM.Excel.cExcelFile.CellHiddenLocked.xlsNormal; // // 报表标题
// int cellformat = 1;
// // int rowindex = 1,colindex = 3;
// // object title = (object)strTitle;
// // excel.WriteValue(ref vt, ref cf, ref ca, ref chl,ref rowindex,ref colindex,ref title,ref cellformat); // int rowIndex = 1;//起始行
// int colIndex = 0; // //取得列标题
// foreach (DataColumn colhead in dt.Columns)
// {
// colIndex++;
// string name = colhead.ColumnName.Trim();
// object namestr = (object)name;
// IDictionaryEnumerator Enum = nameList.GetEnumerator();
// while (Enum.MoveNext())
// {
// if (Enum.Key.ToString().Trim() == name)
// {
// namestr = Enum.Value;
// }
// }
// excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref namestr, ref cellformat);
// } // //取得表格中的数据
// foreach (DataRow row in dt.Rows)
// {
// rowIndex++;
// colIndex = 0;
// foreach (DataColumn col in dt.Columns)
// {
// colIndex++;
// if (col.DataType == System.Type.GetType("System.DateTime"))
// {
// object str = (object)(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); ;
// excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
// }
// else
// {
// object str = (object)row[col.ColumnName].ToString();
// excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
// }
// }
// }
// int ret = excel.CloseFile(); // // if(ret!=0)
// // {
// // //MessageBox.Show(this,"Error!");
// // }
// // else
// // {
// // //MessageBox.Show(this,"请打开文件c:\\test.xls!");
// // }
// return filename; //} #endregion #region 清理过时的Excel文件 private void ClearFile(string FilePath)
{
String[] Files = System.IO.Directory.GetFiles(FilePath);
if (Files.Length > )
{
for (int i = ; i < ; i++)
{
try
{
System.IO.File.Delete(Files[i]);
}
catch
{
} }
}
}
#endregion }
}

[Excel] C#DataToExcel帮助类 (转载)的更多相关文章

  1. [Excel] C# ExcelHelper操作类 (转载)

    点击下载 ExcelHelper.rar 主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Exc ...

  2. C#EXCEL 操作类--C#DataToExcel帮助类

    using System; using System.Diagnostics; //using Excel; namespace DotNet.Utilities {     /// <summ ...

  3. Excel导入导出帮助类

    /// <summary>    /// Excel导入导出帮助类    /// 记得引入 NPOI    /// 下载地址   http://npoi.codeplex.com/rele ...

  4. C#导出数据到Excel通用的方法类

    导出数据到Excel通用的方法类,请应对需求自行修改. 资源下载列表 using System.Data; using System.IO; namespace IM.Common.Tools { p ...

  5. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

  6. Workbook导出excel封装的工具类

    在实际中导出excel非常常见,于是自己封装了一个导出数据到excel的工具类,先附上代码,最后会写出实例和解释.支持03和07两个版本的 excel. HSSF导出的是xls的excel,XSSF导 ...

  7. Delphi Excel导入 的通用程序转载

    Delphi Excel导入 的通用程序 (-- ::)转载▼ 标签: it 分类: Delphi相关 步骤: 连excel(自己知道其格式,最好是没个字段在数据一一对应) 读excel数据,填入到数 ...

  8. Excel解析easyexcel工具类

    Excel解析easyexcel工具类 easyexcel解决POI解析Excel出现OOM <!-- https://mvnrepository.com/artifact/com.alibab ...

  9. Java基础学习总结(49)——Excel导入导出工具类

    在项目的pom文件中引入 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifac ...

随机推荐

  1. git rebase实战

    在develop分支上rebase另外一个分支master,是将master作为本地,develop作为远端来处理的. 最后的效果是,develop分支看起来像是在master分支的最新的节点之后才进 ...

  2. maven 下载 源码和javadoc命令

    1:Maven命令下载源码和javadocs 当在IDE中使用Maven时如果想要看引用的jar包中类的源码和javadoc需要通过maven命令下载这些源码,然后再进行引入,通过mvn命令能够容易的 ...

  3. 基于开源软件在Azure平台建立大规模系统的最佳实践

    作者 王枫 发布于2014年5月28日 前言 Microsoft Azure 是微软公有云的唯一解决方案.借助这一平台,用户可以以多种方式部署和发布自己的应用. 这是一个开放的平台,除了对于Windo ...

  4. c# 如何通过反射 获取\设置属性值

    c# 如何通过反射 获取\设置属性值 //定义类public class MyClass{public int Property1 { get; set; }}static void Main(){M ...

  5. 使用Hexo搭建github博客步骤,超简便

    categories: 工具 tags: git Windows 搭建博客 你只需要node环境和一个github账号就可以开工啦! 本教程适合于Windows环境,Mac教程也大同小异 利用hexo ...

  6. vs2010 更新jQuery智能提示包

    vs2010 更新jQuery只能提示包时,可以直接在NuGet中更新 jquery-2.1.0-vsdoc.js jquery-2.1.0.js jquery-2.1.0.min.js jquery ...

  7. strcpy,memcpy,内存块重叠

    前段时间准备面试,看了一些库函数的实现,在看到memcpy时,发现有处理source和destination所指内存有重叠的情况,而strcpy没有,特别模仿库函数写了这个函数,并进行了测试.以下是具 ...

  8. vijosP1037搭建双塔

    vijosP1037搭建双塔 链接:https://vijos.org/p/1037 [思路] DP. [代码] #include<iostream> #include<cstrin ...

  9. HTML5与CSS3权威指南.pdf4

    拖放API HTML5实现了直接拖放操作API,简化HTML4利用mousedown.mousemove等事件实现的操作 实现拖放的步骤 1要将被拖动元素的draggable属性设置为true,img ...

  10. bat坐拥大数据。数据挖掘/大数据给他们带来什么。

    阿里巴巴CTO即阿里云负责人王坚博士说过一句话:云计算和大数据,你们都理解错了.   实际上,对于大数据究竟是什么业界并无共识.大数据并不是什么新鲜事物.信息革命带来的除了信息的更高效地生产.流通和消 ...