码迷,mamicode.com
首页 > Windows程序 > 详细

C# 操作Excel

时间:2020-09-18 00:44:22      阅读:60      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!