C# 操作Excel

2020-12-22 04:26

阅读:748

标签:writing   type   lsh   fail   info   并且   对象   类库   system   

前期准备:安装微软Excel,需要调用excel类库,Microsoft.Excel XXX Object Library

 1 sing System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 using Microsoft.Office.Interop.Excel;//添加Excel类库命名空间
 7 
 8 namespace TestForExcel
 9 {
10     public class ExcelPrinter
11     {
12         public void SaveFile()
13         {            
14 
15             //创建Excel工作簿对象
16             Microsoft.Office.Interop.Excel.Application excelApp = new Application();          
17 
18             //设置禁止弹出保存和覆盖的询问提示框
19             excelApp.DisplayAlerts = false;
20             excelApp.AlertBeforeOverwriting = false;
21 
22             //获取已创建工作簿路径(这里的路径是在工程文件debug\bin下,并且excel文件事先准备好的,不知道如何调用excelApp创建...)
23             string excelBookPath = Environment.CurrentDirectory + "\\Studentinfo.xlsx";
24 
25             //定义工作簿workbook
26             Workbook wb = excelApp.Workbooks.Open(excelBookPath);
27             //Workbook wb = excelApp.Workbooks.Add(excelBookPath);           
28             Worksheet objSheet = (Worksheet)excelApp.Workbooks[1].Worksheets[1];
29 
30             //往表中写入数据
31             objSheet.Cells[2, 3] = "";
32             objSheet.Cells[2, 5] = "2062084";
33             objSheet.Cells[4, 3] = "";
34             objSheet.Cells[4, 5] = "20";
35 
36             #region excel其他操作
37             //增加工作表worksheet
38             //Worksheet objSheet = (Worksheet)excelApp.Worksheets.Add(Type.Missing,Type.Missing, 1,XlSheetType.xlWorksheet);
39 
40             //修改sheet名字
41             //objSheet.Name = "SJ";
42 
43             //计算工作表个数
44             //int sheetCount = excelApp.Workbooks[1].Worksheets.Count;
45             //Worksheet oo = (Worksheet)excelApp.Workbooks[1].Worksheets[sheetCount];
46             //oo.Name = "dddww";
47 
48             //另存为:
49             //wb.SaveAs(@"D:\code\C#\TestForExcel\TestForExcel\bin\Debug\3a.xlsx");
50 
51             //关闭工作簿
52             //wb.Close(false);
53 
54             //打开Excel
55             //excelApp.Visible = true;
56             #endregion
57             //保存
58             wb.Save();
59 
60             //关闭Excel进程
61             excelApp.Quit();
62             System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
63             excelApp = null;
64                       
65         }
66     }
67 }

一般情况下各种fail,都是因为excel类库安装不匹配。。。

C# 操作Excel

标签:writing   type   lsh   fail   info   并且   对象   类库   system   

原文地址:https://www.cnblogs.com/pandora2050/p/13664906.html


评论


亲,登录后才可以留言!