c#操作excel 设置单元格值,打开excle文件,保存excel

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

namespace DataTransfer
{
public class OprationExcle
{
private Microsoft.Office.Interop.Excel.Application m_objExcelApp;
private Microsoft.Office.Interop.Excel.Workbook m_objExcelWorkBook;
private Microsoft.Office.Interop.Excel.Worksheet m_objExcelWorkSheet;
private Microsoft.Office.Interop.Excel.Worksheet m_objTempWorkSheet;
/// <summary>
/// application 进程
/// </summary>
public OprationExcle()
{
try
{
m_objExcelApp = new Microsoft.Office.Interop.Excel.Application();
m_objExcelApp.DisplayAlerts = false;
}
catch (Exception e)
{
Quit();
throw new Exception(e.Message);
}

}
/// <summary>
/// 退出进程
/// </summary>
public void Quit()
{
m_objExcelApp.Quit();
}
/// <summary>
/// 打开excel
/// </summary>
/// <param name="p_strExcelFileName"></param>
public void OpenExcelFile(string p_strExcelFileName)
{
m_objExcelWorkBook = m_objExcelApp.Workbooks.Open(p_strExcelFileName, Type.Missing,
true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
}
/// <summary>
/// 选择sheet
/// </summary>
/// <param name="p_strSheetName"></param>
public void SelectSheet(string p_strSheetName)
{
m_objExcelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)m_objExcelWorkBook.Sheets[p_strSheetName];
}
/// <summary>
/// 设置单元格的值
/// </summary>
/// <param name="p_intRows"></param>
/// <param name="p_intColumn"></param>
/// <param name="p_strValue"></param>
public void SetCellValue(int p_intRows, int p_intColumn, string p_strValue)
{

try
{
if (p_intRows <= 65528)
{
m_objExcelWorkSheet.Cells[p_intRows, p_intColumn] = p_strValue;
}
}
catch (Exception ex)
{
Quit();
throw new Exception(ex.Message);
}
}
/// <summary>
/// 设置合并单元格
/// </summary>
/// <param name="c"></param>
/// <param name="b"></param>
public void SetArange(string c, string b)
{
m_objExcelWorkSheet.get_Range(c, b).Merge(Type.Missing); ;
}
/// <summary>
/// 保存excel
/// </summary>
/// <param name="p_strName"></param>
public void SaveAs(string p_strName)
{

m_objExcelWorkBook.SaveAs(p_strName, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
/// <summary>
/// 设置单元格的颜色
/// </summary>
/// <param name="sRow"></param>
/// <param name="sCol"></param>
/// <param name="eRow"></param>
/// <param name="eCol"></param>
/// <param name="colorIndex"></param>
public void SetRangeBackground(int sRow, int sCol, int eRow, int eCol, int colorIndex)
{
//range = m_objExcelWorkSheet.get_Range(m_objExcelWorkSheet.Cells[sRow, sCol], m_objExcelWorkSheet.Cells[eRow, eCol]);
//range.Interior.ColorIndex = colorIndex;
}
}
}

posted @ 2016-07-28 10:51  吃葡萄不吐葡萄脾  阅读(326)  评论(0编辑  收藏  举报