This class can be used to create a Excel workbook and setting values in a particular cell.
Many times we need to save some values in excel and do some calculations programatically.
We usually automate performance calculation and calculating percentage of improvement using the following class.
This class helps us to save your time in excel automation and performance calculation.
Usage:
//Excel Open
CExcelHelper objExcel = new CExcelHelper();
objExcel.createExcel();
string str="Sample";
objExcel.SetValue(2, 1, ref str);
Many times we need to save some values in excel and do some calculations programatically.
We usually automate performance calculation and calculating percentage of improvement using the following class.
This class helps us to save your time in excel automation and performance calculation.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; class CExcelHelper { public int m_nCol; public int m_nRow; private Excel.Application m_oXL; private Excel._Workbook m_oWB; private Excel._Worksheet m_oSheet; private Excel.Range m_oRng; public void createExcel() { try { //Start Excel and get Application object. m_oXL = new Excel.Application(); m_oXL.Visible = true; //Get a new workbook. m_oWB = (Excel._Workbook)(m_oXL.Workbooks.Add(Missing.Value)); m_oSheet = (Excel._Worksheet)m_oWB.ActiveSheet; m_oXL.Visible = true; m_oXL.UserControl = true; } catch (Exception theException) { ErrMsg(ref theException); } } public bool SetValue(int nRow, int nCol, ref string strValue) { //Row and col should from 1S if (nRow < 1 || nCol < 1) return false; bool bRet = true; try { m_oSheet.Cells[nRow, nCol] = strValue; } catch (Exception e) { ErrMsg(ref e); return false; } return bRet; } public void CloseExcel() { m_oXL.Quit(); } private void ErrMsg(ref Exception theException) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat(errorMessage, theException.Message); errorMessage = String.Concat(errorMessage, " Line: "); errorMessage = String.Concat(errorMessage, theException.Source); MessageBox.Show(errorMessage, "Error"); } public bool ApplyFormula(String strRangeStart, String strRangeEnd, string strFormula) { bool bRet = true; try { m_oRng = m_oSheet.get_Range(strRangeStart, strRangeEnd); m_oRng.Formula = strFormula; } catch (Exception e) { ErrMsg(ref e); return false; } return bRet; } private string RangeAddress(Excel.Range rng) { return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1); } public string CellAddress(int row, int col) { return RangeAddress(m_oSheet.Cells[row, col]); } }
//Excel Open
CExcelHelper objExcel = new CExcelHelper();
objExcel.createExcel();
string str="Sample";
objExcel.SetValue(2, 1, ref str);