博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Excel Wrapper
阅读量:7050 次
发布时间:2019-06-28

本文共 10100 字,大约阅读时间需要 33 分钟。

using System;

using System.Diagnostics;
using System.Collections;
using System.Data;
using System.Web;
using System.Runtime.InteropServices;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections.Generic;
using System.Drawing;
namespace VQP.Common
{
    public class ExcelWrapper
    {
        private string _ReportTemplate_Excel_FileName = null;
        private Excel.Application _Excel = null;
        private Excel.Workbooks _WorkBooks = null;
        private Excel.Workbook _WorkBook = null;
        private Excel.Sheets _WorkSheets = null;
        private Excel.Worksheet _WorkSheet = null;
        private string _password = "";
        private string _filenamepath = "";
        private int _WorkSheetCount = 0;
        public int WorkSheetCount
        {
            get { return _WorkSheetCount; }
            set { _WorkSheetCount = value; }
        }
        private string _excelversion;
        public string ExcelVersion
        {
            get { return _excelversion; }
            set { _excelversion = value; }
        }
        private List<int> _vqpSheetCountList = null;
        public List<int> VqpSheetCountList
        {
            get { return _vqpSheetCountList; }
            set { _vqpSheetCountList = value; }
        }
        private Hashtable _hsSheetName = new Hashtable();
        public Hashtable HsSheetName
        {
            get
            {
                return _hsSheetName;
            }
            set
            {
                _hsSheetName = value;
            }
        }
        public ExcelWrapper()
        {
        }
        /// <summary>
        /// open excel
        /// </summary>
        /// <param name="strFileName"></param>
        public ExcelWrapper(string strFileName, string strPassword)
        {
            _ReportTemplate_Excel_FileName = strFileName;
            _Excel = new Excel.Application();
            _Excel.Visible = false;
            _Excel.DisplayAlerts = false;
            _WorkBooks = _Excel.Workbooks;
            this._password = strPassword.Trim();
            //_WorkBook = _WorkBooks.Open(strFileName, 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);
            if (this._password.Trim().Length == 0)
            {
                _WorkBook = _WorkBooks.Open(strFileName, 0, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            }
            else
            {
                _WorkBook = _WorkBooks.Open(strFileName, 0, false, Missing.Value, this._password, this._password, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                //_WorkBook.WritePassword =
            }
            _WorkSheetCount = _Excel.Sheets.Count;
            _vqpSheetCountList = ValidExcelSheetName();
            this._filenamepath = strFileName;
            _Excel.Visible = false;
            this._excelversion = _Excel.Version;
        }
        #region Read excel function
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private List<int> ValidExcelSheetName()
        {
            List<int> sheetList = new List<int>();
            for (int i = 1; i <= _WorkSheetCount; i++)
            {
                string strSheetName = ((Excel.Worksheet)_WorkBook.Sheets[i]).Name;
                if (strSheetName.ToUpper().StartsWith("Q-"))
                {
                    sheetList.Add(i);
                    if (!_hsSheetName.Contains(i))
                    {
                        this._hsSheetName.Add(i, strSheetName);
                    }
                }
            }
            return sheetList;
        }
        private string SetNullToEmpty(Object mValue)
        {
            if (null == mValue || string.Empty.Equals(mValue))
            {
                return string.Empty;
            }
            else
            {
                return mValue.ToString();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sheetIndex"></param>
        /// <param name="rowIndex"></param>
        /// <param name="columnIndex"></param>
        /// <returns></returns>
        public string GetExcelCellValue(int sheetIndex, int rowIndex, int columnIndex)
        {
            string strResult = string.Empty;
            if (_WorkSheetCount >= sheetIndex)
            {
                Excel.Worksheet sheet = (Excel.Worksheet)_WorkBook.Sheets[sheetIndex];
                //strResult = SetNullToEmpty(((Microsoft.Office.Interop.Excel.Range)sheet.Cells[rowIndex, columnIndex]).Text);
                strResult = SetNullToEmpty(((Microsoft.Office.Interop.Excel.Range)sheet.Cells[rowIndex, columnIndex]).Value2);
            }
            return strResult;
        }
        public string GetExcelCellText(int sheetIndex, int rowIndex, int columnIndex)
        {
            string strResult = string.Empty;
            if (_WorkSheetCount >= sheetIndex)
            {
                Excel.Worksheet sheet = (Excel.Worksheet)_WorkBook.Sheets[sheetIndex];
                strResult = SetNullToEmpty(((Microsoft.Office.Interop.Excel.Range)sheet.Cells[rowIndex, columnIndex]).Text);
            }
            return strResult;
        }
        #endregion
        #region Write excel function
        public void SetWorkSheetName(int sheetIndex, string strWorkSheetName)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            _WorkSheet.Name = strWorkSheetName;
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void CopyWorkSheet(int sheetIndex, string sheetName)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            _WorkSheet.Copy(Missing.Value, _WorkSheets[_WorkSheets.Count]);
            Release(_WorkSheet);
            _WorkSheet = (Excel.Worksheet)_WorkSheets[_WorkSheets.Count];
            _WorkSheet.Name = sheetName;
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void HideSheet(int sheetIndex)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            _WorkSheet.Visible = Excel.XlSheetVisibility.xlSheetHidden;
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void WriteCell(int sheetIndex, int row, int col, string strCellValue)
        {
            try
            {
                if (strCellValue == null)
                {
                    strCellValue = "";
                }
                strCellValue = strCellValue.Trim();
                strCellValue = strCellValue.Replace("\n\t", String.Empty);
                strCellValue = strCellValue.Replace("\n", String.Empty);
                strCellValue = strCellValue.Replace("'", "\'");
                _WorkSheets = _WorkBook.Sheets;
                _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
                _WorkSheet.Unprotect(this._password);
                _WorkSheet.Cells[row, col] = strCellValue.ToString();
                //(_WorkSheet.Cells[row, col] as Excel.Range).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                //(_WorkSheet.Cells[row, col] as Excel.Range).Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
                Excel.Range excelRange = _WorkSheet.Cells[row, col] as Excel.Range;
                if (excelRange != null)
                {
                    excelRange.Borders.LineStyle = 1;
                    excelRange.Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                    string commentTxt = "Value has been corrected by VQP system.";
                    if (excelRange.Comment != null)
                    {
                        excelRange.Comment.Delete();
                    }
                    excelRange.AddComment(commentTxt);
                    excelRange.Comment.Visible = true;
                }
            }
            catch(Exception ex)
            {
                Console.Write(ex.ToString());
            }
            //Release(_WorkSheet);
            //Release(_WorkSheets);
        }
        public void WriteComment(string strCellValue, int RowStart, int ColStart, int sheetIndex)
        {
            WriteCell(sheetIndex, RowStart, ColStart, strCellValue);
        }
        public void DeleteColumn(int col, int sheetIndex)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            Excel.Range oColumn = (Excel.Range)_WorkSheet.Cells[1, col];
            oColumn.EntireColumn.Delete(Missing.Value);
            Release(oColumn);
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void DeleteRow(int row, int sheetIndex)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            Excel.Range oRow = (Excel.Range)_WorkSheet.Cells[row, 1];
            oRow.EntireRow.Delete(Missing.Value);
            Release(oRow);
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void InsertRow(int row, int sheetIndex)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            Excel.Range oRow = (Excel.Range)_WorkSheet.Cells[row, 1];
            oRow.EntireRow.Copy(oRow.EntireRow);
            oRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            Release(oRow);
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void InsertRows(int sheetIndex, int row, int insertingRowCount)
        {
            _WorkSheets = _WorkBook.Sheets;
            _WorkSheet = (Excel.Worksheet)_WorkSheets[sheetIndex];
            for (int i = 1; i <= insertingRowCount; i++)
            {
                Excel.Range oRow = (Excel.Range)_WorkSheet.Rows[row, 1];
                oRow.EntireRow.Copy(oRow.EntireRow);
                oRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
                Release(oRow);
            }
            Release(_WorkSheet);
            Release(_WorkSheets);
        }
        public void SaveAs(string strExcelName)
        {
            //_WorkBook.SaveAs(strExcelName, Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            //if (System.IO.Path.GetExtension(strExcelName).ToLower() == ".xlsx")
            //    exclVersion = Excel.XlFileFormat.xlOpenXMLWorkbook;//Excel 2007版本
            Excel.XlFileFormat exclVersion = Excel.XlFileFormat.xlWorkbookNormal;//Excel 2003版本  
            _WorkBook.SaveAs(strExcelName, exclVersion, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
        }
        #endregion
        #region Excel common function
        public bool IsExistSheetName(string sheetName)
        {
            object sheet = null;
            try
            {
                sheet = _WorkBook.Sheets.get_Item(sheetName);
            }
            catch
            {
                sheet = null;
            }
            return (sheet != null);
        }
        public int GetSheetIndex(string sheetName)
        {
            if(IsExistSheetName(sheetName))
            {
                foreach (Excel.Worksheet sheet in _WorkBook.Sheets)
                {
                    if (sheet.Name == sheetName)
                    {
                        return sheet.Index;
                    }
                }
            }
            return -1;
        }
        #endregion
        /// <summary>
        /// close excel
        /// </summary>
        public void Close()
        {
            _WorkBook.Close(false, Missing.Value, Missing.Value);
            _WorkBooks.Close();
            _Excel.Quit();
            Release(_WorkSheet);
            Release(_WorkSheets);
            Release(_WorkBook);
            Release(_WorkBooks);
            Release(_Excel);
            KillUselessExcelProcess();
        }
        /// <summary>
        /// release excel
        /// </summary>
        /// <param name="obj"></param>
        private void Release(Object obj)
        {
            if (obj == null)
            {
                return;
            }
            try
            {
                int nResult = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                if (nResult > 0)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                }
            }
            catch
            {
            }
            finally
            {
                obj = null;
            }
        }
        /// <summary>
        /// kill excel process
        /// </summary>
        private void KillUselessExcelProcess()
        {
            GC.Collect();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                try
                {
                    if (p.ProcessName.ToUpper().StartsWith("EXCEL"))
                    {
                        //if (p.StartTime.AddSeconds(15) < TimeParser.Now)
                        //{
                        //   p.Kill();
                        //}
                        p.Kill();
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}

转载地址:http://gjpol.baihongyu.com/

你可能感兴趣的文章
33 ArcToolBox学习系列之数据管理工具箱——投影与变换(Projections and Transformations)未完待续……...
查看>>
iOS 9 的新功能 universal links
查看>>
内容滚动条 案例
查看>>
移动浏览器中实现拨打电话,调用sms,发送email
查看>>
docker 搭建小型的node开发环境。
查看>>
angular和vue的对比学习之路
查看>>
Java第九次作业
查看>>
JS动态获取 Url 参数
查看>>
RSA被顶级分析公司评为安全信息和事件管理领导厂商
查看>>
.Net Discovery系“.NET技术”列之-深入理解平台机制与性能影响 (中)
查看>>
Amazon SES SPF和DKIM设置教程
查看>>
【简讯】微软拟发布开源VB6
查看>>
轻量级的Web服务器Nginx0.9.0 开发版发布
查看>>
1.文件重命名工具
查看>>
【java】json格式解析
查看>>
4_1 wp8数据绑定与独立存储空间[wp8特色开发与编程技巧]
查看>>
Linux开始结束ping命令
查看>>
openfire invalid sid 404
查看>>
开源一款私藏Management Studio插件,ProjkyAddin,送给所有使用SQLServer的园友们
查看>>
jQuery判断checkbox是否选中的3种方法
查看>>