1. 程式人生 > >c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll讀取Excel檔案

c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll讀取Excel檔案

1、引用Microsoft.Office.Interop.Excel.dll

2、引用名稱空間、使用別名

using System.Reflection;

using Excel = Microsoft.Office.Interop.Excel;

3.寫入excel

寫入函式

 public void ToExcel(string strTitle)
        {
            int nMax = 9;
            int nMin = 4;

            int rowCount = nMax - nMin + 1;//總行數

            const int columnCount = 4;//總列數



            //建立Excel物件

            Excel.Application excelApp = new Excel.ApplicationClass();



            //新建工作簿

            Excel.Workbook workBook = excelApp.Workbooks.Add(true);



            //新建工作表

            Excel.Worksheet worksheet = workBook.ActiveSheet as Excel.Worksheet;



            ////設定標題

            //Excel.Range titleRange = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]);//選取單元格

            //titleRange.Merge(true);//合併單元格

            //titleRange.Value2 = strTitle; //設定單元格內文字

            //titleRange.Font.Name = "宋體";//設定字型

            //titleRange.Font.Size = 18;//字型大小

            //titleRange.Font.Bold = false;//加粗顯示

            //titleRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中

            //titleRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中

            //titleRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//設定邊框

            //titleRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//邊框常規粗細



            //設定表頭

            string[] strHead = new string[columnCount] { "序號", "範圍", "分組1", "分組2" };

            int[] columnWidth = new int[4] { 8, 16, 8, 10 };

            for (int i = 0; i < columnCount; i++)
            {

                //Excel.Range headRange = worksheet.Cells[2, i + 1] as Excel.Range;//獲取表頭單元格

                Excel.Range headRange = worksheet.Cells[1, i + 1] as Excel.Range;//獲取表頭單元格,不用標題則從1開始

                headRange.Value2 = strHead[i];//設定單元格文字

                headRange.Font.Name = "宋體";//設定字型

                headRange.Font.Size = 12;//字型大小

                headRange.Font.Bold = false;//加粗顯示

                headRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中

                headRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中

                headRange.ColumnWidth = columnWidth[i];//設定列寬

              //  headRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//設定邊框

               // headRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//邊框常規粗細

            }



            //設定每列格式

            for (int i = 0; i < columnCount; i++)
            {

                //Excel.Range contentRange = worksheet.get_Range(worksheet.Cells[3, i + 1], worksheet.Cells[rowCount - 1 + 3, i + 1]);

                Excel.Range contentRange = worksheet.get_Range(worksheet.Cells[2, i + 1], worksheet.Cells[rowCount - 1 + 3, i + 1]);//不用標題則從第二行開始

                contentRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中

                contentRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中

                //contentRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//設定邊框

               // contentRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//邊框常規粗細

                contentRange.WrapText = true;//自動換行

                contentRange.NumberFormatLocal = "@";//文字格式

            }



            //填充資料

            for (int i = nMin; i <= nMax; i++)
            {

                int k = i - nMin;

                //excelApp.Cells[k + 3, 1] = string.Format("{0}", k + 1);

                //excelApp.Cells[k + 3, 2] = string.Format("{0}-{1}", i - 0.5, i + 0.5);

                //excelApp.Cells[k + 3, 3] = string.Format("{0}", k + 3);

                //excelApp.Cells[k + 3, 4] = string.Format("{0}", k + 4);

                excelApp.Cells[k + 2, 1] = string.Format("{0}", k + 1);

                excelApp.Cells[k + 2, 2] = string.Format("{0}-{1}", i - 0.5, i + 0.5);

                excelApp.Cells[k + 2, 3] = string.Format("{0}", k + 3);

                excelApp.Cells[k + 2, 4] = string.Format("{0}", k + 4);

            }



            //設定Excel可見

            excelApp.Visible = true;

        }

寫入按鈕函式:

private void button1_Click(object sender, EventArgs e)
        {
            ToExcel("方式3");

        }

結果:

4.讀取excel

新增一個opendiog用於選擇要讀取的excel

名稱空間

using System.Diagnostics;

讀取函式:

        private void OpenExcel(string strFileName)
        {
            object missing = System.Reflection.Missing.Value;
            Excel.Application excel = new Excel.ApplicationClass();//lauch excel application
            if (excel == null)
            {
               this.label1.Text="Can't access excel";
            }
            else
            {
                excel.Visible = false; excel.UserControl = true;
                // 以只讀的形式開啟EXCEL檔案
                Excel.Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
                 missing, missing, missing, true, missing, missing, missing, missing, missing);
                //取得第一個工作薄
                Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
                //取得總記錄行數    (包括標題列)
                int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行數
                //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列數
                //取得資料範圍區域   (不包括標題列)  
                Excel.Range rng1 = ws.Cells.get_Range("A2", "A" + rowsint);  
                Excel.Range rng2 = ws.Cells.get_Range("B2", "B" + rowsint);
                Excel.Range rng3 = ws.Cells.get_Range("C2", "C" + rowsint);  
                Excel.Range rng4 = ws.Cells.get_Range("D2", "D" + rowsint);  
                object[,] arry1 = (object[,])rng1.Value2;   //get range's value
                object[,] arry2 = (object[,])rng2.Value2;
                object[,] arry3 = (object[,])rng3.Value2;   //get range's value
                object[,] arry4 = (object[,])rng4.Value2;
                //將新值賦給一個數組
                string[,] arry = new string[rowsint - 1, 4];
                //for (int i = 1; i <= rowsint - 1; i++)
                for (int i = 1; i <= rowsint - 2; i++)
                {
                   
                    arry[i - 1, 0] = arry1[i, 1].ToString();
                  
                    arry[i - 1, 1] = arry2[i, 1].ToString();

                    arry[i - 1, 2] = arry3[i, 1].ToString();
                   
                    arry[i - 1, 3] = arry4[i, 1].ToString();
                }
                string a = "";
                for (int i = 0; i <= rowsint - 3; i++)
                {
                    a += arry[i, 0] + "|" + arry[i, 1] + "|" + arry[i, 2] + "|" + arry[i, 3]+"\n";
                   
                }
               this.label1.Text=a;
            }
            excel.Quit(); excel = null;
          Process[] procs = Process.GetProcessesByName("excel");
            foreach (Process pro in procs)
            {
                pro.Kill();//沒有更好的方法,只有殺掉程序
            }
            GC.Collect();
        }

讀取按鈕程式碼:

  private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                OpenExcel(openFileDialog.FileName);
            }

        }

 結果;