C# ExcelHelper 寫入、刪標籤頁、替換

using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

namespace Platform
{
    public class ExcelHelper
    {
        /// <summary>
        /// 將數據表寫入Excel,不含表頭,從指定的位置開始寫
        /// </summary>
        /// <param name="excelPath">excel文件路徑</param>
        /// <param name="dts">數據表列表</param>
        /// <param name="startPosition">開始位置</param>
        public void ExportDts2ServalExcelSheets(string excelPath, List<System.Data.DataTable> dts, List<string> startPositions)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbooks wbks = app.Workbooks;
            object missing = System.Reflection.Missing.Value;
            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
            app.Visible = true;
            Sheets shs = _wbk.Sheets;
            //輸出


            for (int sheetIndex = 1; sheetIndex <= shs.Count; sheetIndex++)
            {
                _Worksheet _wsh = (Microsoft.Office.Interop.Excel.Worksheet)shs.get_Item(sheetIndex);
                int indexTab = dts.FindIndex(delegate (System.Data.DataTable d) { return d.TableName == _wsh.Name; });
                if (indexTab < 0)
                    continue;

                _wsh.Activate();
                //輸出內容
                System.Data.DataTable dt = dts[indexTab];
                if (dt.Rows.Count > 0)
                {
                    Range r = _wsh.get_Range(startPositions[indexTab], Missing.Value);
                    r = r.get_Resize(dt.Rows.Count, dt.Columns.Count);
                    object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count];
                    for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
                    {
                        for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
                        {
                            cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString();
                        }
                    }
                    r.set_Value(Missing.Value, cellData);
                }
                _wbk.Save();//保存
            }




            _wbk.Close(false);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量
            _wbk = null;

            wbks.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放
            wbks = null;
            app.Quit();
            KeyMyExcelProcess.Kill(app);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少
            app = null;
            System.GC.Collect(); //回收資源清內存
        }

        /// <summary>
        /// 將Excel中每個Sheet頁的A1內容,其中的oldValue替換成newValue
        /// </summary>
        /// <param name="excelPath"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void ModifyExcelSheetTableHead(string excelPath, string oldValue, string newValue)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbooks wbks = app.Workbooks;
            object missing = System.Reflection.Missing.Value;
            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
            app.Visible = true;
            Sheets shs = _wbk.Sheets;
            //輸出

            for (int i = 1; i <= shs.Count; i++)
            {
                _Worksheet _wsh = (Microsoft.Office.Interop.Excel.Worksheet)shs.get_Item(i);
                Range r = _wsh.get_Range("A1", Missing.Value);
                if (r.Text != "")
                {
                    string wholeSentence = r.Value.ToString();
                    wholeSentence = r.Value.Replace(oldValue, newValue);
                    r.set_Value(Missing.Value, wholeSentence);
                }
                _wbk.Save();//保存
            }

            _wbk.Close(false);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量
            _wbk = null;

            wbks.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放
            wbks = null;
            app.Quit();
            KeyMyExcelProcess.Kill(app);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少
            app = null;
            System.GC.Collect(); //回收資源清內存
        }


        /// <summary>
        /// 將Excel中每個Sheet頁的頁名稱,如果不含該指定的名稱,則刪除
        /// </summary>
        /// <param name="excelPath"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void RemoveExcelSheetWithoutCityName(string excelPath,string thisName,string exceptionSheetName)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbooks wbks = app.Workbooks;
            object missing = System.Reflection.Missing.Value;
            app.DisplayAlerts = false;
            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
            app.Visible = true;
            Sheets shs = _wbk.Sheets;
            for (int i = shs.Count; i >=1 ; i--)
            {
                if (!shs.get_Item(i).Name.Contains(thisName)&& shs.get_Item(i).Name!=exceptionSheetName)
{ shs.get_Item(i).Delete(); } } _wbk.Save(); _wbk.Close(false); System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量 _wbk = null; wbks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放 wbks = null; app.Quit(); KeyMyExcelProcess.Kill(app); System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少 app = null; System.GC.Collect(); //回收資源清內存 } /// <summary> /// 將數據表寫入Excel文件的不同新創建的Sheet頁,含表頭 /// </summary> public void ExportDts2ServalExcelSheets(string excelPath, List<System.Data.DataTable> dts) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Workbooks wbks = app.Workbooks; object missing = System.Reflection.Missing.Value; _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing); app.Visible = true; Sheets shs = _wbk.Sheets; //輸出 for (int i = 1; i <= shs.Count; i++) { _Worksheet _wsh = shs.get_Item(i); System.Data.DataTable dt = dts.Find(delegate (System.Data.DataTable d) { return d.TableName == _wsh.Name; }); if (dt == null) continue; _wsh.Activate(); ////輸出表頭 object[] data = new object[dt.Columns.Count]; Range r = _wsh.get_Range("A1", Missing.Value); Range newRange = r.get_Resize(1, dt.Columns.Count);//表頭,所以僅有一行 newRange.set_Value(Type.Missing, GetColumnObjs(dt.Columns)); //輸出內容 if (dt.Rows.Count > 0) { r = _wsh.get_Range("A2", Missing.Value); r = r.get_Resize(dt.Rows.Count, dt.Columns.Count); object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count]; for (int iRow = 0; iRow < dt.Rows.Count; iRow++) { for (int iCol = 0; iCol < dt.Columns.Count; iCol++) { cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString(); } } r.set_Value(Missing.Value, cellData); } _wbk.Save();//保存 } _wbk.Close(false); System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量 _wbk = null; wbks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放 wbks = null; app.Quit(); KeyMyExcelProcess.Kill(app); System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少 app = null; System.GC.Collect(); //回收資源清內存 } private string Object2String(object obj) { try { string result = obj.ToString(); return result; } catch { return ""; } } private DateTime Object2Date(object obj) { if (obj is null) return DateTime.Parse("2050-01-01"); try { if (DateTime.TryParse(obj.ToString(), out DateTime dt)) return dt; else return DateTime.Parse("2050-01-01"); } catch { return DateTime.Parse("2050-01-01"); } } public float Object2Float(object obj) { if (obj is null) return 0; if (float.TryParse(obj.ToString(), out float result)) return result; else return 0; } private int Object2Int(object obj) { if (int.TryParse(obj.ToString(), out int result)) return result; else return 0; } private String GetExcelColumnName(int i) { List<string> list = new List<string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM", "AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ", "BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG", "CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ","DA","DB","DC","DD", "DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ","EA", "EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ" }; return list[i - 1]; } /// <summary> /// 得到一個列的所有列名 /// </summary> private object[] GetColumnObjs(System.Data.DataColumnCollection dc) { object[] array = new object[dc.Count]; for (int i = 0; i < array.Length; i++) { DataColumn dataColumn = dc[i]; array[i] = dataColumn.ColumnName; } return array; } /// <summary> /// 關閉Excel進程 /// </summary> public class KeyMyExcelProcess { [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); public static void Kill(Microsoft.Office.Interop.Excel.Application excel) { try { IntPtr t = new IntPtr(excel.Hwnd); //得到這個句柄,具體作用是得到這塊內存入口 int k = 0; GetWindowThreadProcessId(t, out k); //得到本進程唯一標誌k System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到對進程k的引用 p.Kill(); //關閉進程k } catch (System.Exception ex) { throw ex; } } } } }

 

using Microsoft.Office.Interop.Excel;using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Reflection;using System.Runtime.InteropServices;using System.Text;
namespace 信息統計平臺配套工具{    public class ExcelHelper    {        /// <summary>        /// 將數據表寫入Excel,不含表頭,從指定的位置開始寫        /// </summary>        /// <param name="excelPath">excel文件路徑</param>        /// <param name="dts">數據表列表</param>        /// <param name="startPosition">開始位置</param>        public void ExportDts2ServalExcelSheets(string excelPath, List<System.Data.DataTable> dts, List<string> startPositions)        {            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            Workbooks wbks = app.Workbooks;            object missing = System.Reflection.Missing.Value;            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);            app.Visible = true;            Sheets shs = _wbk.Sheets;            //輸出

            for (int sheetIndex = 1; sheetIndex <= shs.Count; sheetIndex++)            {                _Worksheet _wsh = (Microsoft.Office.Interop.Excel.Worksheet)shs.get_Item(sheetIndex);                int indexTab = dts.FindIndex(delegate (System.Data.DataTable d) { return d.TableName == _wsh.Name; });                if (indexTab < 0)                    continue;
                _wsh.Activate();                //輸出內容                System.Data.DataTable dt = dts[indexTab];                if (dt.Rows.Count > 0)                {                    Range r = _wsh.get_Range(startPositions[indexTab], Missing.Value);                    r = r.get_Resize(dt.Rows.Count, dt.Columns.Count);                    object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count];                    for (int iRow = 0; iRow < dt.Rows.Count; iRow++)                    {                        for (int iCol = 0; iCol < dt.Columns.Count; iCol++)                        {                            cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString();                        }                    }                    r.set_Value(Missing.Value, cellData);                }                _wbk.Save();//保存            }



            _wbk.Close(false);            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量            _wbk = null;
            wbks.Close();            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放            wbks = null;            app.Quit();            KeyMyExcelProcess.Kill(app);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少            app = null;            System.GC.Collect(); //回收資源清內存        }
        /// <summary>        /// 將Excel中每個Sheet頁的A1內容,其中的oldValue替換成newValue        /// </summary>        /// <param name="excelPath"></param>        /// <param name="oldValue"></param>        /// <param name="newValue"></param>        public void ModifyExcelSheetTableHead(string excelPath, string oldValue, string newValue)        {            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            Workbooks wbks = app.Workbooks;            object missing = System.Reflection.Missing.Value;            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);            app.Visible = true;            Sheets shs = _wbk.Sheets;            //輸出
            for (int i = 1; i <= shs.Count; i++)            {                _Worksheet _wsh = (Microsoft.Office.Interop.Excel.Worksheet)shs.get_Item(i);                Range r = _wsh.get_Range("A1", Missing.Value);                if (r.Text != "")                {                    string wholeSentence = r.Value.ToString();                    wholeSentence = r.Value.Replace(oldValue, newValue);                    r.set_Value(Missing.Value, wholeSentence);                }                _wbk.Save();//保存            }
            _wbk.Close(false);            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量            _wbk = null;
            wbks.Close();            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放            wbks = null;            app.Quit();            KeyMyExcelProcess.Kill(app);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少            app = null;            System.GC.Collect(); //回收資源清內存        }

        /// <summary>        /// 將Excel中每個Sheet頁的頁名稱,如果不含該城市名,則刪除        /// </summary>        /// <param name="excelPath"></param>        /// <param name="oldValue"></param>        /// <param name="newValue"></param>        public void RemoveExcelSheetWithoutCityName(string excelPath,string cityName,string exceptionSheetName)        {            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            Workbooks wbks = app.Workbooks;            object missing = System.Reflection.Missing.Value;            app.DisplayAlerts = false;            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);            app.Visible = true;            Sheets shs = _wbk.Sheets;            for (int i = shs.Count; i >=1 ; i--)            {                if (!shs.get_Item(i).Name.Contains(cityName)&& shs.get_Item(i).Name!=exceptionSheetName)                {                    shs.get_Item(i).Delete();                }            }            _wbk.Save();            _wbk.Close(false);            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量            _wbk = null;
            wbks.Close();            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放            wbks = null;            app.Quit();            KeyMyExcelProcess.Kill(app);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少            app = null;            System.GC.Collect(); //回收資源清內存        }


        /// <summary>        /// 將數據表寫入Excel文件的不同新創建的Sheet頁,含表頭        /// </summary>        public void ExportDts2ServalExcelSheets(string excelPath, List<System.Data.DataTable> dts)        {            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            Workbooks wbks = app.Workbooks;            object missing = System.Reflection.Missing.Value;            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);            app.Visible = true;            Sheets shs = _wbk.Sheets;            //輸出
            for (int i = 1; i <= shs.Count; i++)            {                _Worksheet _wsh = shs.get_Item(i);                System.Data.DataTable dt = dts.Find(delegate (System.Data.DataTable d) { return d.TableName == _wsh.Name; });                if (dt == null)                    continue;
                _wsh.Activate();                ////輸出表頭                object[] data = new object[dt.Columns.Count];                Range r = _wsh.get_Range("A1", Missing.Value);                Range newRange = r.get_Resize(1, dt.Columns.Count);//表頭,所以僅有一行                newRange.set_Value(Type.Missing, GetColumnObjs(dt.Columns));
                //輸出內容                if (dt.Rows.Count > 0)                {                    r = _wsh.get_Range("A2", Missing.Value);                    r = r.get_Resize(dt.Rows.Count, dt.Columns.Count);                    object[,] cellData = new object[dt.Rows.Count, dt.Columns.Count];                    for (int iRow = 0; iRow < dt.Rows.Count; iRow++)                    {                        for (int iCol = 0; iCol < dt.Columns.Count; iCol++)                        {                            cellData[iRow, iCol] = dt.Rows[iRow][iCol].ToString();                        }                    }                    r.set_Value(Missing.Value, cellData);                }                _wbk.Save();//保存            }
            _wbk.Close(false);            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量            _wbk = null;
            wbks.Close();            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放            wbks = null;            app.Quit();            KeyMyExcelProcess.Kill(app);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少            app = null;            System.GC.Collect(); //回收資源清內存        }        //(2022年2季度)  YYYY年MM月
        /// <summary>        /// 將數據表寫入Excel文件的不同新創建的Sheet頁        /// </summary>        public void ExcelMark(string excelPath)        {            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();            Workbooks wbks = app.Workbooks;            object missing = System.Reflection.Missing.Value;            _Workbook _wbk = wbks.Open(excelPath, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);            app.Visible = true;            Sheets shs = _wbk.Sheets;
            //輸出            for (int sheetIndex = 1; sheetIndex <= shs.Count; sheetIndex++)            {                _Worksheet _wsh = (Microsoft.Office.Interop.Excel.Worksheet)shs.get_Item(sheetIndex);                _wsh.Activate();                switch (_wsh.Name)                { //lightpink    turquoise violet lightgreen  gold  deepskyblue   orange  yellow  pulm    tan   orange
                    case "提交情況":                        for (int i = 1; i < _wsh.UsedRange.Rows.Count; i++)                        {                            for (int j = 1; j <= _wsh.UsedRange.Columns.Count; j++)                            {                                string info = Object2String(_wsh.Cells[j][i + 1].Text);                                if (info == "未提交")                                {                                    _wsh.Range[GetExcelColumnName(j) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);                                }                            }                        }                        _wbk.Save();//保存                        break;                    case "附件1表1項目":                        for (int i = 1; i < _wsh.UsedRange.Rows.Count; i++)                        {                            //1.1、【項目名稱】爲空,或包含引號、分號、問號、斜槓等不合理字符                            string xiangmumingcheng = Object2String(_wsh.Cells[9][i + 1].Text);                            if (xiangmumingcheng.Contains("\"") || xiangmumingcheng.Contains(";") || xiangmumingcheng.Contains("\\") || xiangmumingcheng.Contains("?") || xiangmumingcheng == "")                            {                                _wsh.Range[GetExcelColumnName(9) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);                            }                            //1.2、【項目投資額】>一億 * 【所含單位工程數】 或     【項目投資額】<【所含單位工程數】                            float zongtouzie = Object2Float(_wsh.Cells[12][i + 1].Text);                            int danweigongchengshu = Object2Int(_wsh.Cells[14][i + 1].Text);                            if (zongtouzie > danweigongchengshu * 10000 || zongtouzie < danweigongchengshu)                            {                                _wsh.Range[GetExcelColumnName(12) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Turquoise);                                _wsh.Range[GetExcelColumnName(14) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Turquoise);                            }                            //1.3、【所含單位工程數】爲0                            if (danweigongchengshu == 0)                            {                                _wsh.Range[GetExcelColumnName(14) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gold);                            }                        }                        _wbk.Save();//保存                        break;                    case "附件1表1標段":                        for (int i = 1; i < _wsh.UsedRange.Rows.Count; i++)                        {                            //2.1、【標段名稱】爲空,或包含引號、分號、問號、斜槓等不合理字符                            string biaoduanmingcheng = Object2String(_wsh.Cells[14][i + 1].Text);                            if (biaoduanmingcheng.Contains("\"") || biaoduanmingcheng.Contains(";") || biaoduanmingcheng.Contains("\\") || biaoduanmingcheng.Contains("?") || biaoduanmingcheng == "")                            {                                _wsh.Range[GetExcelColumnName(14) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);                            }                            //2.2、【標段合同價款】>一億 * 【單位工程數】   或  <10萬*單位工程數                            float hetongjiakuan = Object2Float(_wsh.Cells[16][i + 1].Text);                            int danweigongchengshu = Object2Int(_wsh.Cells[29][i + 1].Text);                            if (hetongjiakuan > danweigongchengshu * 10000 || hetongjiakuan < danweigongchengshu * 10)                            {                                _wsh.Range[GetExcelColumnName(16) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Turquoise);                                _wsh.Range[GetExcelColumnName(29) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Turquoise);                            }                            //2.3、【所含單位工程數】爲空                            if (danweigongchengshu == 0)                            {                                _wsh.Range[GetExcelColumnName(29) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gold);                            }
                            //2.4、【標段開工日期】比【標段竣工日期】晚,或日期空缺,異常                            DateTime kaigongriqi = Object2Date(_wsh.Cells[17][i + 1].Value);                            DateTime jungongriqi = Object2Date(_wsh.Cells[19][i + 1].Text);                            if (kaigongriqi > jungongriqi || kaigongriqi < DateTime.Parse("1990-01-01") || kaigongriqi > DateTime.Parse("2050-01-01"))                            {                                _wsh.Range[GetExcelColumnName(17) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);                            }                            if (kaigongriqi > jungongriqi || jungongriqi < DateTime.Parse("1990-01-01") || jungongriqi > DateTime.Parse("2050-01-01"))                            {                                _wsh.Range[GetExcelColumnName(19) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);                            }                        }                        _wbk.Save();//保存                        break;                    case "附件1表1單位工程":                        for (int i = 1; i < _wsh.UsedRange.Rows.Count; i++)                        {                            //3.1、【單位工程名稱】爲空,或包含引號、分號、問號、斜槓等不合理字符                            string danweigongchengmingcheng = Object2String(_wsh.Cells[30][i + 1].Text);                            if (danweigongchengmingcheng.Contains("\"") || danweigongchengmingcheng.Contains(";") || danweigongchengmingcheng.Contains("\\") || danweigongchengmingcheng.Contains("?") || danweigongchengmingcheng == "")                            {                                _wsh.Range[GetExcelColumnName(30) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);                            }                            //3.2、【單位工程開工日期】【單位工程竣工日期】空缺,異常,或單位工程的【開工】比【竣工】晚
                            DateTime kaigongriqi = Object2Date(_wsh.Cells[44][i + 1].Value);                            DateTime jungongriqi = Object2Date(_wsh.Cells[45][i + 1].Value);                            if (kaigongriqi > jungongriqi || kaigongriqi < DateTime.Parse("1990-01-01") || kaigongriqi > DateTime.Parse("2050-01-01"))                            {                                _wsh.Range[GetExcelColumnName(44) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Salmon);                            }                            if (kaigongriqi > jungongriqi || jungongriqi < DateTime.Parse("1990-01-01") || jungongriqi > DateTime.Parse("2050-01-01"))                            {                                _wsh.Range[GetExcelColumnName(45) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Salmon);                            }
                            //3.3、【單位工程開工日期】比【標段開工日期】早                            DateTime biaoduankaigongriqi = Object2Date(_wsh.Cells[17][i + 1].Value);                            if (biaoduankaigongriqi > kaigongriqi)                            {                                _wsh.Range[GetExcelColumnName(17) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.PaleGreen);                            }
                            //3.4、【單位工程竣工日期】比【標段竣工日期】晚                            DateTime biaoduanjungongriqi = Object2Date(_wsh.Cells[19][i + 1].Value);                            if (biaoduanjungongriqi < jungongriqi)                            {                                _wsh.Range[GetExcelColumnName(19) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LimeGreen);                            }                            //3.5、【建築面積】大於30萬平方米  或  ( 【建築面積】>200 and  單位工程名稱中包含“門”)                            float jianzhumianji = Object2Float(_wsh.Cells[32][i + 1].Text);                            if (jianzhumianji > 30 ||(danweigongchengmingcheng.Contains("門") && jianzhumianji>0.02))                            {                                _wsh.Range[GetExcelColumnName(32) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Turquoise);                            }                            //3.6、單位工程的【形象進度】爲“已竣工”時,【單位工程竣工日期】不應爲空,或爲默認的“2050-01-01”                            string xingxiangjindu = Object2String(_wsh.Cells[35][i + 1].Text);                            if (xingxiangjindu == "已竣工" && jungongriqi == DateTime.Parse("2050-01-01"))                            {                                _wsh.Range[GetExcelColumnName(35) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SandyBrown);                                _wsh.Range[GetExcelColumnName(45) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SandyBrown);                            }
                            //好像邏輯不合適                            ////3.7、【形象進度】不是“已完工”或“已竣工”時,【是否建立信用檔案】已填寫爲“是”                            //string shifousheliyongjiuxingbiaopai = Object2String(_wsh.Cells[42][i + 1].Text);                            //string shifoushelijianlixinyongdangan = Object2String(_wsh.Cells[43][i + 1].Text);                            //if (!xingxiangjindu.Contains("已完工") || !xingxiangjindu.Contains("已竣工"))                            //{                            //    if (shifoushelijianlixinyongdangan == "是")                            //    {                            //        _wsh.Range[GetExcelColumnName(35) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Violet);                            //        _wsh.Range[GetExcelColumnName(43) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Violet);                            //    }                            //}                                                        //太複雜還沒有處理                            ////3.8、標段內各單位工程的【形象進度】均爲“已竣工”時,【標段竣工日期】不應爲空,或爲默認的“2050 - 01 - 01”                            //if (xingxiangjindu == "已竣工" && biaoduanjungongriqi == DateTime.Parse("2050-01-01"))                            //{                            //    _wsh.Range[GetExcelColumnName(35) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Violet);                            //    _wsh.Range[GetExcelColumnName(19) + (i + 1).ToString()].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Violet);                            //}                        }                        _wbk.Save();//保存                        break;
                    default: break;                }


            }            _wbk.Save();//保存            _wbk.Close(false);            System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbk); //通知COM控件,釋放變量            _wbk = null;
            wbks.Close();            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbks);//所有用過的變量都要釋放            wbks = null;            app.Quit();            KeyMyExcelProcess.Kill(app);            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);//一個也不能少            app = null;            System.GC.Collect(); //回收資源清內存        }
        private string Object2String(object obj)        {            try            {                string result = obj.ToString();                return result;            }            catch            {                return "";            }        }
        private DateTime Object2Date(object obj)        {            if (obj is null)                return DateTime.Parse("2050-01-01");
            try            {                if (DateTime.TryParse(obj.ToString(), out DateTime dt))                    return dt;                else                    return DateTime.Parse("2050-01-01");            }            catch            {                return DateTime.Parse("2050-01-01");            }        }
        public float Object2Float(object obj)        {            if (obj is null)                return 0;
            if (float.TryParse(obj.ToString(), out float result))                return result;            else                return 0;        }        private int Object2Int(object obj)        {            if (int.TryParse(obj.ToString(), out int result))                return result;            else                return 0;        }

        private String GetExcelColumnName(int i)        {            List<string> list = new List<string>() { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",                "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM",                "AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ",                "BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG",                "CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ","DA","DB","DC","DD",                "DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ","EA",                "EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ" };            return list[i - 1];        }        /// <summary>        /// 得到一個列的所有列名        /// </summary>        private object[] GetColumnObjs(System.Data.DataColumnCollection dc)        {            object[] array = new object[dc.Count];            for (int i = 0; i < array.Length; i++)            {                DataColumn dataColumn = dc[i];                array[i] = dataColumn.ColumnName;            }            return array;        }
        /// <summary>        /// 關閉Excel進程        /// </summary>        public class KeyMyExcelProcess        {            [DllImport("User32.dll", CharSet = CharSet.Auto)]            public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);            public static void Kill(Microsoft.Office.Interop.Excel.Application excel)            {                try                {                    IntPtr t = new IntPtr(excel.Hwnd);  //得到這個句柄,具體作用是得到這塊內存入口                    int k = 0;                    GetWindowThreadProcessId(t, out k);  //得到本進程唯一標誌k                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);  //得到對進程k的引用                    p.Kill();   //關閉進程k                }                catch (System.Exception ex)                {                    throw ex;                }            }        }    }}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章