C#用OFFICE自带的库读写EXCEL

使用Office自带的库
前提是本机须安装office才能运行,且不同的office版本之间可能会有兼容问题,从Nuget下载 Microsoft.Office.Interop.Excel
在这里插入图片描述

using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

        private void btn_Office_Click(object sender, EventArgs e)
        {
            string importExcelPath = "E:\\import.xlsx";
            string exportExcelPath = "E:\\export.xlsx";
            //创建
            Excel.Application xlApp = new Excel.Application();
            xlApp.DisplayAlerts = false;
            xlApp.Visible = false;
            xlApp.ScreenUpdating = false;
            //打开Excel
            Excel.Workbook xlsWorkBook = xlApp.Workbooks.Open(importExcelPath, 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, System.Type.Missing);

            //处理数据过程,更多操作方法自行百度
            Excel.Worksheet sheet = xlsWorkBook.Worksheets[1];//工作薄从1开始,不是0
            sheet.Cells[1, 1] = "test";

            //另存
            xlsWorkBook.SaveAs(exportExcelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //关闭Excel进程
            ClosePro(xlApp, xlsWorkBook);
        }
        public void ClosePro(Excel.Application xlApp, Excel.Workbook xlsWorkBook)
        {
            if (xlsWorkBook != null)
                xlsWorkBook.Close(true, Type.Missing, Type.Missing);
            xlApp.Quit();
            // 安全回收进程
            System.GC.GetGeneration(xlApp);
            IntPtr t = new IntPtr(xlApp.Hwnd);   //获取句柄
            int k = 0;
            GetWindowThreadProcessId(t, out k);   //获取进程唯一标志
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();     //关闭进程
        }

百度AI生成的代码

using System;  
using System.Runtime.InteropServices;  
using Excel = Microsoft.Office.Interop.Excel;  
  
class Program  
{  
    static void Main(string[] args)  
    {  
        // 创建Excel应用程序对象  
        Excel.Application excelApp = new Excel.Application();  
  
        // 打开Excel文件  
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\example.xlsx");  
  
        // 获取第一个工作表  
        Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];  
  
        // 获取单元格的值  
        object value = excelWorksheet.Range["A1"].Value;  
  
        // 打印单元格的值  
        Console.WriteLine(value);  
  
        // 关闭Excel文件和应用程序对象  
        excelWorkbook.Close();  
        excelApp.Quit();  
    }  
}

你可能感兴趣的:(c#,excel,c#)