• c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件


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

    2、引用命名空间、使用别名

    [csharp] view plaincopy
     
    1. using System.Reflection;  
    2.   
    3. using Excel = Microsoft.Office.Interop.Excel;  


     

    3.写入excel

    写入函数

    [csharp] view plaincopy
     
    1. public void ToExcel(string strTitle)  
    2.        {  
    3.            int nMax = 9;  
    4.            int nMin = 4;  
    5.   
    6.            int rowCount = nMax - nMin + 1;//总行数  
    7.   
    8.            const int columnCount = 4;//总列数  
    9.   
    10.   
    11.   
    12.            //创建Excel对象  
    13.   
    14.            Excel.Application excelApp = new Excel.ApplicationClass();  
    15.   
    16.   
    17.   
    18.            //新建工作簿  
    19.   
    20.            Excel.Workbook workBook = excelApp.Workbooks.Add(true);  
    21.   
    22.   
    23.   
    24.            //新建工作表  
    25.   
    26.            Excel.Worksheet worksheet = workBook.ActiveSheet as Excel.Worksheet;  
    27.   
    28.   
    29.   
    30.            ////设置标题  
    31.   
    32.            //Excel.Range titleRange = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnCount]);//选取单元格  
    33.   
    34.            //titleRange.Merge(true);//合并单元格  
    35.   
    36.            //titleRange.Value2 = strTitle; //设置单元格内文本  
    37.   
    38.            //titleRange.Font.Name = "宋体";//设置字体  
    39.   
    40.            //titleRange.Font.Size = 18;//字体大小  
    41.   
    42.            //titleRange.Font.Bold = false;//加粗显示  
    43.   
    44.            //titleRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中  
    45.   
    46.            //titleRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中  
    47.   
    48.            //titleRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//设置边框  
    49.   
    50.            //titleRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//边框常规粗细  
    51.   
    52.   
    53.   
    54.            //设置表头  
    55.   
    56.            string[] strHead = new string[columnCount] { "序号", "范围", "分组1", "分组2" };  
    57.   
    58.            int[] columnWidth = new int[4] { 8, 16, 8, 10 };  
    59.   
    60.            for (int i = 0; i < columnCount; i++)  
    61.            {  
    62.   
    63.                //Excel.Range headRange = worksheet.Cells[2, i + 1] as Excel.Range;//获取表头单元格  
    64.   
    65.                Excel.Range headRange = worksheet.Cells[1, i + 1] as Excel.Range;//获取表头单元格,不用标题则从1开始  
    66.   
    67.                headRange.Value2 = strHead[i];//设置单元格文本  
    68.   
    69.                headRange.Font.Name = "宋体";//设置字体  
    70.   
    71.                headRange.Font.Size = 12;//字体大小  
    72.   
    73.                headRange.Font.Bold = false;//加粗显示  
    74.   
    75.                headRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中  
    76.   
    77.                headRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中  
    78.   
    79.                headRange.ColumnWidth = columnWidth[i];//设置列宽  
    80.   
    81.              //  headRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//设置边框  
    82.   
    83.               // headRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//边框常规粗细  
    84.   
    85.            }  
    86.   
    87.   
    88.   
    89.            //设置每列格式  
    90.   
    91.            for (int i = 0; i < columnCount; i++)  
    92.            {  
    93.   
    94.                //Excel.Range contentRange = worksheet.get_Range(worksheet.Cells[3, i + 1], worksheet.Cells[rowCount - 1 + 3, i + 1]);  
    95.   
    96.                Excel.Range contentRange = worksheet.get_Range(worksheet.Cells[2, i + 1], worksheet.Cells[rowCount - 1 + 3, i + 1]);//不用标题则从第二行开始  
    97.   
    98.                contentRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中  
    99.   
    100.                contentRange.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中  
    101.   
    102.                //contentRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//设置边框  
    103.   
    104.               // contentRange.Borders.Weight = Excel.XlBorderWeight.xlThin;//边框常规粗细  
    105.   
    106.                contentRange.WrapText = true;//自动换行  
    107.   
    108.                contentRange.NumberFormatLocal = "@";//文本格式  
    109.   
    110.            }  
    111.   
    112.   
    113.   
    114.            //填充数据  
    115.   
    116.            for (int i = nMin; i <= nMax; i++)  
    117.            {  
    118.   
    119.                int k = i - nMin;  
    120.   
    121.                //excelApp.Cells[k + 3, 1] = string.Format("{0}", k + 1);  
    122.   
    123.                //excelApp.Cells[k + 3, 2] = string.Format("{0}-{1}", i - 0.5, i + 0.5);  
    124.   
    125.                //excelApp.Cells[k + 3, 3] = string.Format("{0}", k + 3);  
    126.   
    127.                //excelApp.Cells[k + 3, 4] = string.Format("{0}", k + 4);  
    128.   
    129.                excelApp.Cells[k + 2, 1] = string.Format("{0}", k + 1);  
    130.   
    131.                excelApp.Cells[k + 2, 2] = string.Format("{0}-{1}", i - 0.5, i + 0.5);  
    132.   
    133.                excelApp.Cells[k + 2, 3] = string.Format("{0}", k + 3);  
    134.   
    135.                excelApp.Cells[k + 2, 4] = string.Format("{0}", k + 4);  
    136.   
    137.            }  
    138.   
    139.   
    140.   
    141.            //设置Excel可见  
    142.   
    143.            excelApp.Visible = true;  
    144.   
    145.        }  


     

    写入按钮函数:

    [csharp] view plaincopy
     
    1. private void button1_Click(object sender, EventArgs e)  
    2.         {  
    3.             ToExcel("方式3");  
    4.   
    5.         }  

    结果:

    4.读取excel

    添加一个opendiog用于选择要读取的excel

    命名空间

    [csharp] view plaincopy
     
    1. using System.Diagnostics;  

    读取函数:

    [csharp] view plaincopy
     
    1. private void OpenExcel(string strFileName)  
    2. {  
    3.     object missing = System.Reflection.Missing.Value;  
    4.     Excel.Application excel = new Excel.ApplicationClass();//lauch excel application  
    5.     if (excel == null)  
    6.     {  
    7.        this.label1.Text="Can't access excel";  
    8.     }  
    9.     else  
    10.     {  
    11.         excel.Visible = false; excel.UserControl = true;  
    12.         // 以只读的形式打开EXCEL文件  
    13.         Excel.Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,  
    14.          missing, missing, missing, true, missing, missing, missing, missing, missing);  
    15.         //取得第一个工作薄  
    16.         Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);  
    17.         //取得总记录行数    (包括标题列)  
    18.         int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数  
    19.         //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数  
    20.         //取得数据范围区域   (不包括标题列)    
    21.         Excel.Range rng1 = ws.Cells.get_Range("A2", "A" + rowsint);    
    22.         Excel.Range rng2 = ws.Cells.get_Range("B2", "B" + rowsint);  
    23.         Excel.Range rng3 = ws.Cells.get_Range("C2", "C" + rowsint);    
    24.         Excel.Range rng4 = ws.Cells.get_Range("D2", "D" + rowsint);    
    25.         object[,] arry1 = (object[,])rng1.Value2;   //get range's value  
    26.         object[,] arry2 = (object[,])rng2.Value2;  
    27.         object[,] arry3 = (object[,])rng3.Value2;   //get range's value  
    28.         object[,] arry4 = (object[,])rng4.Value2;  
    29.         //将新值赋给一个数组  
    30.         string[,] arry = new string[rowsint - 1, 4];  
    31.         //for (int i = 1; i <= rowsint - 1; i++)  
    32.         for (int i = 1; i <= rowsint - 2; i++)  
    33.         {  
    34.              
    35.             arry[i - 1, 0] = arry1[i, 1].ToString();  
    36.             
    37.             arry[i - 1, 1] = arry2[i, 1].ToString();  
    38.   
    39.             arry[i - 1, 2] = arry3[i, 1].ToString();  
    40.              
    41.             arry[i - 1, 3] = arry4[i, 1].ToString();  
    42.         }  
    43.         string a = "";  
    44.         for (int i = 0; i <= rowsint - 3; i++)  
    45.         {  
    46.             a += arry[i, 0] + "|" + arry[i, 1] + "|" + arry[i, 2] + "|" + arry[i, 3]+"\n";  
    47.              
    48.         }  
    49.        this.label1.Text=a;  
    50.     }  
    51.     excel.Quit(); excel = null;  
    52.   Process[] procs = Process.GetProcessesByName("excel");  
    53.     foreach (Process pro in procs)  
    54.     {  
    55.         pro.Kill();//没有更好的方法,只有杀掉进程  
    56.     }  
    57.     GC.Collect();  
    58. }  


     

    读取按钮代码:

    [csharp] view plaincopy
     
    1. private void button1_Click(object sender, EventArgs e)  
    2.       {  
    3.           if (openFileDialog.ShowDialog() == DialogResult.OK)  
    4.           {  
    5.               OpenExcel(openFileDialog.FileName);  
    6.           }  
    7.   
    8.       }  


     

     结果;

  • 相关阅读:
    idea双击打不开没反应的解决办法
    Golang Learn Log #0
    获取请求header的各种方法
    Linux 指令
    Windows下Anaconda的安装和简单使用
    如何把Python脚本导出为exe程序
    C++星号的含义
    仓库盘点功能-ThinkPHP_学习随笔
    详解html中的元老级元素:“table”
    IE在开发工具启动的情况下(打开F12)时 JS才能执行
  • 原文地址:https://www.cnblogs.com/victorgui/p/3991282.html
Copyright © 2020-2023  润新知