using Microsoft.Office.Interop.Excel;
using System;
using System.IO;
using System.Reflection; namespace ECIT.ProjectManagementSystem.Common
{
public class ExcelHelper : IDisposable
{
#region 成员变量 private object missing = Missing.Value;
private Application app;
private Workbook workBook;
public Worksheet workSheet; public void setWorkSheet(int i)
{
workSheet = (Worksheet)workBook.Worksheets[i];
} #endregion 成员变量 #region 公共属性 /// <summary>
/// WorkSheet数量
/// </summary>
public int WorkSheetCount
{
get { return workBook.Sheets.Count; }
} #endregion 公共属性 #region 构造函数 /// <summary>
/// 构造函数,新建一个工作簿
/// </summary>
public ExcelHelper()
{
app = new Application();
workBook = app.Workbooks.Add(Type.Missing);
workSheet = (Worksheet)app.Worksheets[];
} /// <summary>
/// 构造函数,打开一个已有的工作簿
/// </summary>
/// <param name="fileName">Excel文件名</param>
public ExcelHelper(string fileName)
{
if (!File.Exists(fileName))
throw new Exception("指定路径的Excel文件不存在!"); app = new Application(); workBook = app.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing); workSheet = (Worksheet)app.Worksheets[];
} #endregion 构造函数 #region 工作表操作 /// <summary>
/// 删除工作表
/// </summary>
/// <param name="i">工作表的序号</param>
public void RemoveSheet(int i)
{
Worksheet worksheet = (Worksheet)app.Worksheets[i];
app.DisplayAlerts = false;
worksheet.Delete();
app.DisplayAlerts = true;
} /// <summary>
/// 增加工作表
/// </summary>
/// <param name="i">工作表的序号</param>
public void AddSheet(int i)
{
app.Worksheets.Add(Type.Missing, Type.Missing, i, XlSheetType.xlWorksheet);
} #endregion 工作表操作 #region 单元格操作 /// <summary>
/// 获得最大行号
/// </summary>
/// <returns></returns>
public int GetUsedRangeRow()
{
return workSheet.UsedRange.Rows.Count;
} /// <summary>
/// 获得最大列号
/// </summary>
/// <returns></returns>
public int GetUsedRangeColumn()
{
return workSheet.UsedRange.Columns.Count;
} /// <summary>
/// 获取单元格的文本内容
/// </summary>
/// <param name="row">行号</param>
/// <param name="column">列号</param>
/// <returns></returns>
public string GetCellText(int row, int column)
{
if (workSheet == null)
return null;
Range range = (Range)workSheet.Cells[row, column];
string cellContent = (range.Value2 == null) ? "" : range.Text.ToString();
return cellContent;
} /// <summary>
/// 赋值单元格
/// </summary>
/// <param name="excelRange"></param>
/// <param name="value"></param>
public void SetValue(ExcelRange excelRange, object value)
{
workSheet.Range[excelRange.ToString()].Value2 = value;
} /// <summary>
/// 设置字体大小
/// </summary>
/// <param name="excelRange"></param>
/// <param name="size"></param>
public void SetFontSize(ExcelRange excelRange, int size)
{
workSheet.Range[excelRange.ToString()].Font.Size = size;
} /// <summary>
/// 设置字体颜色
/// </summary>
/// <param name="excelRange"></param>
/// <param name="color"></param>
public void SetFontColor(ExcelRange excelRange, System.Drawing.Color color)
{
workSheet.Range[excelRange.ToString()].Font.Color = color;
} /// <summary>
/// 设置单元格背景色
/// </summary>
/// <param name="excelRange"></param>
/// <param name="color"></param>
public void SetBackgroundColor(ExcelRange excelRange, System.Drawing.Color color)
{
workSheet.Range[excelRange.ToString()].Interior.Color = color;
} /// <summary>
/// 设置字体粗体
/// </summary>
/// <param name="excelRange"></param>
/// <param name="isBold"></param>
public void SetFontBold(ExcelRange excelRange, bool isBold)
{
workSheet.Range[excelRange.ToString()].Font.Bold = isBold; //设置字体粗体。
} /// <summary>
/// 设置是否有下划线
/// </summary>
/// <param name="excelRange"></param>
/// <param name="isUnderline"></param>
public void SetUnderline(ExcelRange excelRange, bool isUnderline)
{
workSheet.Range[excelRange.ToString()].Font.Underline = isUnderline;
} /// <summary>
/// 设置字体
/// </summary>
/// <param name="excelRange"></param>
/// <param name="fontname"></param>
public void SetFontName(ExcelRange excelRange, string fontname)
{
workSheet.Range[excelRange.ToString()].Font.Name = fontname;
} /// <summary>
/// 设置单元格宽度
/// </summary>
/// <param name="excelRange"></param>
/// <param name="columnwidth"></param>
public void SetColumnWidth(ExcelRange excelRange, int columnwidth)
{
workSheet.Range[excelRange.ToString()].ColumnWidth = columnwidth;
} /// <summary>
/// 文本自动换行
/// </summary>
/// <param name="excelRange"></param>
/// <param name="isWrapText"></param>
public void SetWrapText(ExcelRange excelRange, bool isWrapText)
{
workSheet.Range[excelRange.ToString()].WrapText = isWrapText;
} /// <summary>
/// 文本横向对齐方式
/// </summary>
/// <param name="excelRange"></param>
/// <param name="xlHAlign"></param>
public void SetHorizontalAlignment(ExcelRange excelRange, XlHAlign xlHAlign)
{
workSheet.Range[excelRange.ToString()].HorizontalAlignment = xlHAlign;
} /// <summary>
/// 文本垂直对齐方式
/// </summary>
/// <param name="excelRange"></param>
/// <param name="xlHAlign"></param>
public void SetVerticalAlignment(ExcelRange excelRange, XlHAlign xlHAlign)
{
workSheet.Range[excelRange.ToString()].VerticalAlignment = xlHAlign;
} /// <summary>
/// 自动调整列宽
/// </summary>
/// <param name="excelRange"></param>
public void FitColumn(ExcelRange excelRange)
{
workSheet.Range[excelRange.ToString()].EntireColumn.AutoFit();
} /// <summary>
/// 设置单元格边框
/// </summary>
/// <param name="excelRange"></param>
public void SetBorderAround(ExcelRange excelRange, XlLineStyle LineStyle, XlBorderWeight BorderWeight)
{
workSheet.Range[excelRange.ToString()].BorderAround(LineStyle, BorderWeight, XlColorIndex.xlColorIndexAutomatic, ); //设置区域边框
} /// <summary>
/// 单元格合并动作
/// </summary>
/// <param name="excelRange"></param>
/// <param name="IsMergeCells"></param>
public void MergeCell(ExcelRange excelRange, bool IsMergeCells)
{
workSheet.Range[excelRange.ToString()].MergeCells = IsMergeCells;
} #endregion 单元格操作 #region 图表绘制 /// <summary>
/// 3D柱状图
/// </summary>
/// <param name="excelRange"></param>
/// <param name="left"></param>
/// <param name="top"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="title"></param>
/// <param name="xTitle"></param>
/// <param name="yTitle"></param>
/// <param name="plotBy">XlRowCol.xlRows=数据系列在一列中 XlRowCol.xlColumns=数据系列在一行中</param>
public void Draw3DColumn(ExcelRange excelRange, double left, double top, double width, double height, string title, string xTitle, string yTitle, XlRowCol plotBy)
{
ChartObjects charts = (ChartObjects)workSheet.ChartObjects(Type.Missing);
ChartObject chartObj = charts.Add(left, top, width, height);
Chart chart = chartObj.Chart;
chart.ChartWizard(workSheet.Range[excelRange.ToString()], XlChartType.xl3DColumn, missing, plotBy, , , true, title, xTitle, yTitle, );
} /// <summary>
/// 3D柱状图
/// </summary>
/// <param name="excelRange"></param>
/// <param name="startRange"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="title"></param>
/// <param name="xTitle"></param>
/// <param name="yTitle"></param>
/// <param name="plotBy">XlRowCol.xlRows=数据系列在一列中 XlRowCol.xlColumns=数据系列在一行中</param>
public void Draw3DColumn(ExcelRange excelRange, ExcelRange startRange, double width, double height, string title, string xTitle, string yTitle, XlRowCol plotBy)
{
Draw3DColumn(excelRange, Convert.ToDouble(workSheet.Range[startRange.ToString()].Left), Convert.ToDouble(workSheet.Range[startRange.ToString()].Top), width, height, title, xTitle, yTitle, plotBy);
} /// <summary>
/// 3D饼图
/// </summary>
/// <param name="excelRange"></param>
/// <param name="left"></param>
/// <param name="top"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="title"></param>
public void Draw3DPie(ExcelRange excelRange, double left, double top, double width, double height, string title)
{
ChartObjects charts = (ChartObjects)workSheet.ChartObjects(Type.Missing);
ChartObject chartObj = charts.Add(left, top, width, height);
Chart chart = chartObj.Chart;
chart.ChartWizard(workSheet.Range[excelRange.ToString()], XlChartType.xl3DPie, missing, XlRowCol.xlColumns, , , true, title, missing, missing, );
} /// <summary>
/// 3D饼图
/// </summary>
/// <param name="excelRange"></param>
/// <param name="startRange"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="title"></param>
public void Draw3DPie(ExcelRange excelRange, ExcelRange startRange, double width, double height, string title)
{
Draw3DPie(excelRange, Convert.ToDouble(workSheet.Range[startRange.ToString()].Left), Convert.ToDouble(workSheet.Range[startRange.ToString()].Top), width, height, title);
} #endregion 图表绘制 #region 文件操作 /// <summary>
/// 保存文件
/// </summary>
/// <param name="fileName"></param>
public void SaveFile(string fileName)
{
try
{
workBook.RefreshAll();
workBook.SaveAs(fileName, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing);
}
catch (Exception e)
{
Console.WriteLine(e);
throw e;
}
} #endregion 文件操作 #region 资源回收 private bool disposed = false; ~ExcelHelper()
{
//必须为false
Dispose(false);
} public void Dispose()
{
//必须为true
Dispose(true);
//通知垃圾回收机制不再调用终结器(析构器)
GC.SuppressFinalize(this);
} private void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
// 清理托管资源
} // 清理非托管资源
if (app != null)
{
app.Quit();
app = null;
} GC.Collect();
GC.WaitForPendingFinalizers(); //让类型知道自己已经被释放
disposed = true;
} #endregion 资源回收
} /// <summary>
/// EXCEL单元格操作范围
/// </summary>
public class ExcelRange
{
public string RangeString { get; set; } public ExcelRange(string RangeString)
{
this.RangeString = RangeString;
} /// <summary>
/// 输入Excel的行号和列号获得范围
/// </summary>
/// <param name="x">列号</param>
/// <param name="y">行号</param>
public ExcelRange(int x, int y)
{
this.RangeString = IntToLetter(x) + y.ToString();
} public ExcelRange(int x1, int y1, int x2, int y2)
{
this.RangeString = IntToLetter(x1) + y1.ToString() + ":" + IntToLetter(x2) + y2.ToString();
} public ExcelRange(ExcelRange from, ExcelRange to)
{
this.RangeString = from.RangeString + ":" + to.RangeString;
} static public implicit operator ExcelRange(string value)
{
return new ExcelRange(value);
} static public implicit operator string (ExcelRange ExcelRange)
{
return ExcelRange.RangeString;
} public override string ToString()
{
return RangeString;
} /// <summary>
/// 将Excel列的整数索引值转换为字符索引值
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public static string IntToLetter(int n)
{
if (n > )
throw new Exception("索引超出范围,Excel的列索引不能超过700!"); int i = Convert.ToInt32(n / );
int j = n % ; char c1 = Convert.ToChar(i + );
char c2 = Convert.ToChar(j + ); if (n > )
return c1.ToString() + c2.ToString();
else if (n == )
return "Z";
else
return c2.ToString();
}
}
}

【小丸类库系列】Excel操作类的更多相关文章

  1. 【小丸类库系列】Word操作类

    using Microsoft.Office.Interop.Word; using System; using System.Collections.Generic; using System.Dr ...

  2. C#EXCEL 操作类--C#ExcelHelper操作类

    主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...

  3. Excel 操作类

    转载:http://www.cnblogs.com/fellowcheng/archive/2010/08/21/1805158.html ExcelHelper(Excel2007) Code hi ...

  4. C#常用工具类——Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  5. C# Excel操作类

    /// 常用工具类——Excel操作类 /// <para> ------------------------------------------------</para> / ...

  6. C#常用工具类——Excel操作类(ZT)

    本文转载于: http://www.cnblogs.com/zfanlong1314/p/3916047.html /// 常用工具类——Excel操作类 /// <para> ----- ...

  7. C#封装的VSTO Excel操作类

    自己在用的Excel操作类,因为经常在工作中要操作Excel文件,可是使用vba实现起来实在是不方便,而且编写也很困难,拼接一个字符串都看的眼花. 这个时候C#出现了,发现使用C#来操作Excel非常 ...

  8. C#自定义Excel操作类

    C#自定义Excel操作类,可以用于将DataTable导出到Excel文件,从Excel文件读取数据. using System; using System.IO; using System.Dat ...

  9. C# Excel操作类 ExcelHelper

    实现C#与Excel文件的交互操作,实现以下功能: 1.DataTable 导出到 Excel文件 2.Model数据实体导出到 Excel文件[List<Model>] 3.导出数据到模 ...

随机推荐

  1. 转载Expression Tree揭秘

    概述 在.NET Framework 3.5中提供了LINQ 支持后,LINQ就以其强大而优雅的编程方式赢得了开发人员的喜爱,而各种LINQ Provider更是满天飞,如LINQ to NHiber ...

  2. MFRCC522 SPI无法通讯【worldsing笔记】

    用单片机于MRFC522与单片接时,加上485通讯后出现很诡异的像: 只要485芯片上有收到外部发送的信号时RC522就死掉,经过仿真卡在了SPI的收发部分(等待回复) u8 MFRC522Write ...

  3. Oracle- 表查询

    这些都比较基础,还是重温一下. 一.简单的查询语句1.查询表结构sql>desc dept; (使用PL/SQL Developer查询时,必需在命令窗口才能使用该语句) 2.查询所有列sql& ...

  4. C#.NET数据库访问类DBHelper

    这是一个与C# .NET通用的数据库访问类,包含了工厂模式.事务处理等安全机制. 调用方式: DBHelper db = new DBHelper(); DbCommand cmd = db.GetS ...

  5. 用HTML5 Canvas 做擦除及扩散效果

    2013年的时候曾经使用canvas实现了一个擦除效果的需求,即模拟用户在模糊的玻璃上擦除水雾看到清晰景色的交互效果.好在2012年的时候学习HTML5的时候研究过canvas了,所以在比较短的时间内 ...

  6. Android 文件读写的例子

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...

  7. 实现微信文章页面 http://mp.weixin.qq.com/s?__biz=MjM5MDI3OTAwMg==&amp;mid=200337417&amp;idx=1&amp;sn=5959ed1d722c7da66b

    首先发了一篇文章,在微信后台.复制文章链接管理员 保存到数据库 $notice_list = $db->getAll(" SELECT `title`,`file_url`,`arti ...

  8. android学习日记19--四大组件之BroadcastReciver(广播接收者)

    二.BroadcastReciver(广播接收者) 1.简述 BroadcastReciver位于android.content包下,主要用于对广播消息(Intent)的过滤并响应的控件.可以理解为全 ...

  9. careercup-中等难度 17.8

    17.8 给定一个整数数组(有正数和负数),找出总和最大的连续序列,并返回总和. 解法: 就是求连续子序列的和最大,不过存在一个问题: 假设整个数组都是负数,怎么样才是正确的行为呢?看看这个简单的数组 ...

  10. 解决Windows2008Server上PLSQL登录时报ORA-12557

    公司的Oracle服务端是安装在一台Linux服务器上,版本号为11.1.0.7.0.我们开发的系统部署在Windows 2008 Server(x64),因为偶尔需要调用Oracle数据库,所以最开 ...