您的位置:首页 > 编程语言 > C#

C#读写EXCEL操作的简单封装

2015-10-23 01:04 591 查看
       之前没玩过C#的类的封装,虽然我经常使用AccessHelper,但是这个是别人封装好那给我的。

       刚刚弄了好久C#对EXCEL简单的操作的类的封装。终于搞定。源码如下,注释里面写的很清楚啦。

-------------------------源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using Microsoft.Office.Interop.Excel;

class ExcelHelper
{
#region 属性
///---属性初始化
public static Excel.ApplicationClass xlsx = null;
public static _Workbook workBook = null;
public static _Worksheet workSheet = null;
#endregion

#region 打开一个已经存在的EXCEL文件
///---参数是已经存在的EXCEL的文件路径(含文件格式),当前ACTIVEsheet的 index
///---若路径合理,该该函数将执行赋值操作
///---成功返回 TRUE, 失败返回 FALSE
public static bool InitExcel(string filePathStr, int sheetIndex, ref _Worksheet sheet)
{
try
{
///----
if (null != xlsx)
{
CloseExcelApplication();
}
///----检查路径是否合理
if (string.IsNullOrEmpty(filePathStr))
{
throw new Exception("文件路径不能为空,请重新传值");
}
///---判断文件是否存在
if (!File.Exists(filePathStr))
{
throw new Exception(filePathStr + ", 文件不存在");
}
else
{
///---接下来就是赋值。
///---实例化对象
xlsx = new Excel.ApplicationClass();
workBook = xlsx.Workbooks.Open(filePathStr, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

///---设置xlsx后台运行
xlsx.Visible = false;

///---设置当前活动sheet索引
workSheet = (_Worksheet)workBook.Worksheets.get_Item(sheetIndex);
sheet = workSheet;

return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion

#region 保存文件
/// <summary>
/// ----文件已经存在,
/// </summary>
public static void save()
{
workBook.Save();
}
/// <summary>
/// ----文件另存为
/// ----参数filePathStr 为文件路径(含文件格式)
/// </summary>
public static bool saveAs(string filePathStr)
{
try
{
///--检查文件路径是否为空
if (string.IsNullOrEmpty(filePathStr))
{
throw new Exception("文件路径不能为空");
}
///--检查文件是否存在
if (File.Exists(filePathStr))
{
throw new Exception(filePathStr + "文件已经存在,请从新选择");
}
else
{
///---保存文件
workBook.SaveAs(filePathStr, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion

#region 关闭Excel程序
public static void CloseExcelApplication()
{
try
{
///---置空
workBook = null;
workSheet = null;
if (null != xlsx)
{
xlsx.Workbooks.Close();
xlsx.Quit();
xlsx = null;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
///---系统回收资源
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
#endregion

}

-------------------------准备工作

        1,新建一个C# window窗体应用程序,控件如下:



     2, 新建一个excel表格,向其中写入点数据。



-------------------------添加引用



-------------------------引用属性设置

            在 应用中 找到 Microsoft.Office.Interop.Excel,右键选择属性,按照下图修改为false;



-------------------------添加名称空间

using Microsoft.Office.Interop.Excel;

-------------------------点我试试按钮被单击事件源码

private void button1_Click(object sender, EventArgs e)
{
try
{
///--
_Worksheet sheet = null;
///---文件地址
string filePathStr = System.Windows.Forms.Application.StartupPath + "\\1.xlsx";
///---封装调用
bool b = ExcelHelper.InitExcel(filePathStr, 1, ref sheet);
if (true != b)
{
///---初始化失败
ExcelHelper.CloseExcelApplication();
}
///---获取数据,用messageBox显示单元格数据
Range range = (Range)sheet.Cells[1, 1];
MessageBox.Show((string)range.Text);
///---关闭EXCEL文件,释放资源
ExcelHelper.CloseExcelApplication();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

-------------------------完整源码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace testCassEXCELL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
///--
_Worksheet sheet = null;
///---文件地址
string filePathStr = System.Windows.Forms.Application.StartupPath + "\\1.xlsx";
///---封装调用
bool b = ExcelHelper.InitExcel(filePathStr, 1, ref sheet);
if (true != b)
{
///---初始化失败
ExcelHelper.CloseExcelApplication();
}
///---获取数据,用messageBox显示单元格数据
Range range = (Range)sheet.Cells[1, 1];
MessageBox.Show((string)range.Text);
///---关闭EXCEL文件,释放资源
ExcelHelper.CloseExcelApplication();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息