C#操作Excel[操作系统入门]
前期准备:安装微软Excel,需要调用excel类库,Microsoft.Excel XXX Object Library
1sing System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 56using Microsoft.Office.Interop.Excel;//添加Excel类库命名空间
7
8namespace TestForExcel
9{
10publicclass ExcelPrinter
11 {
12publicvoid 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//获取已创建工作簿路径(这里的路径是在工程文件debugin下,并且excel文件事先准备好的,不知道如何调用excelApp创建...)
23string 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:codeC#TestForExcelTestForExcelinDebug3a.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
原文:https://www.cnblogs.com/pandora2050/p/13664906.html
以上是 C#操作Excel[操作系统入门] 的全部内容, 来源链接: utcz.com/z/519340.html