C#對excel一些基本操作

代碼一般可以直接copy使用,也許會在工程裏面未引用,未引用的要自己添加引用(office com接口引用方式:右鍵工程→addreference→com頁→Microsoft Excel xx.0 Object Library)。以下代碼僅僅打開,給某個單元格設置顏色,然後關閉。

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

namespace TestCsConsole
{
    class Excel_Parser_Impl : IExcel_Parser
    {
        private Microsoft.Office.Interop.Excel.Application      app     = null;
        private Microsoft.Office.Interop.Excel.Workbook         wb      = null;
        private Microsoft.Office.Interop.Excel.Worksheet        ws      = null;
        private Microsoft.Office.Interop.Excel.Range            range   = null;
        private string                                          filePath;

        public  bool LoadFile(string FileName)
        {
            filePath = FileName;
            try
            {
                app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                wb = app.Workbooks.Open(filePath, false, System.Type.Missing, System.Type.Missing, System.Type.Missing,
                    System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
                    System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
                app.Visible = false;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Excel操作出錯:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally
            {
            }
            return true;
        }

        public  void CloseFile()
        {
            wb.Save();
            app.Quit();
            app = null;
            return;
        }

        public  void SetCellColor(string TabSheetName, System.Drawing.Color CellColor, int Col, int Row)
        {
            
            if (true)
            {
                try
                {
                    ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(TabSheetName);
                    range = (Range)ws.Cells[Row, Col];
                    range.Interior.Color = System.Drawing.ColorTranslator.ToOle(CellColor);
                    
                    app.DisplayAlerts = false;
                    app.AlertBeforeOverwriting = false;
                    
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Excel操作出錯:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                }
            }
            return;
        }
    }
}



發佈了52 篇原創文章 · 獲贊 7 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章