VS2008环境下C#对Excel的操作 [C#] (收集转载)

摘要:
使用Excel=Microsoft.Office.Interop.Excel;2、 使用命名空间中的ApplicationClass类创建Excel对象。如果传递了描述Excel文件名的字符串类型,则将使用作为模板传递的Excel文件创建新工作簿。此常量可以是XlWBATemplate枚举类型的值,例如xlWBSTChart、xlWBATExcel4IntMacroSheet、xlWBATExcel4MicroSheet或xlWBATWorksheet。如果忽略此参数,Excel将根据SheetInNewWorkbook属性的值创建新工作簿。Excel.Workbook工作簿=MyExcel.Workbooks.Open;4、 创建工作表表单。6、保存Excel文档。确定当前活动的表并将其保存。

开发环境:

Windows XP

Microsoft Visual Studio 2008

Office 2003

最近开发从数据库导出数据到Excel的功能,需要在C#中执行对Excel的操作。在网上搜索到这类的资料很多,但实际用到自己的代码里总不那么尽如人意。经过多次试验,终于能按照自己理想中的方式执行完毕。现补充自己在实践中遇到的情况以供参考。示例如下:

一、要在C#中操作Excel,必须使用命名空间Microsoft.Office.Inteop.Excel。该命名空间必须在使用前从References中添加。添加完毕后在文件头用using语句进行关联。

using Excel=Microsoft.Office.Interop.Excel;

二、使用命名空间中的ApplicationClass类来创建Excel对象。

Excel.ApplicationClass MyExcel=new Excel.ApplicationClass();

三、创建工作簿。

方法一:Excel.Workbook workbook=MyExcel.Workbooks.Add(true);

方法二:Excel.Workbook workbook=MyExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

这里,MSDN里对Workbooks类的Add方法的定义如下:

Workbook Add( [In, Optional] object Template);

对Template参数的解释是这样的:

Template

Optional Object. Determines how the new workbook is created. If this argument is a string specifying the name of an existing Microsoft Excel file, the new workbook is created with the specified file as a template. If this argument is a constant, the new workbook contains a single sheet of the specified type. Can be one of the following XlWBATemplate constants: xlWBATChart, xlWBATExcel4IntlMacroSheet, xlWBATExcel4MacroSheet, or xlWBATWorksheet. If this argument is omitted, Microsoft Excel creates a new workbook with a number of blank sheets (the number of sheets is set by the SheetsInNewWorkbook property).

也就是说,Workbooks.Add的参数是个可选的object类型,这个参数定义了新的工作簿的创建方式。如果传递的是一个描述Excel文件名的string类型,那么新的工作簿会以你所传递的Excel文件为模板来创建。如果传递的参数是一个常量,那么这个新的工作簿只会包含一个单独的sheet表单。这个常量可以是XlWBATemplate枚举类型的值,如:xlWBSTChart,xlWBATExcel4IntMacroSheet,xlWBATExcel4MacroSheet,或xlWBATWorksheet。如果这个参数被省略了,Excel会按照SheetInNewWorkbook属性的值来创建一个新的工作簿。

通常情况下,使用true或null,表明工作簿在默认文档下创建,或者使用枚举值      XlWBATemplate.xlWBATWorksheet,也可以传入一个已经存在的excel完整文件名。

方法三:打开一个已经存在的Excel文件。

Excel.Workbook workbook=MyExcel.Workbooks.Open(Environment.CurrentDirectory+"/SampleExcel.xls",0, false, 5, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value,true, false, System.Reflection.Missing.Value, false, false, false);    

四、创建工作页sheet表单。

方法一:Excel.Worksheet worksheet =(Worksheet)workbook.Worksheets[1];       //选择sheet1

Workbook.Worksheets属性在MSDN里的定义是:

Returns a Sheets collection that represents all the worksheets in the specified workbook. Read-only Sheets object.

这是一个只读的sheets集合。

方法二:Excel.Worksheet worksheet = workbook.ActiveSheet as Excel.Worksheet;

           //或者写成Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet; 

在MSDN里对ActiveSheet是接口_Workbook的属性。它的定义如下:

object ActiveSheet {get;}

Returns an object that represents the active sheet (the sheet on top) in the active workbook or in the specified window or workbook. Returns Nothing if no sheet is active. Read-only.

这是一个只读属性,它返回一个object类型值,这个值代表了屏幕顶端的活动工作簿的活动sheet表单。

而Workbook类实现了_Workbook接口。

五、设置格式。

这个部分网上资料比较多。略。

六、保存Excel文档。

            //设置禁止弹出保存和覆盖的询问提示框。这两句代码至关重要,而且必不可少,否则,保存时会弹出“是否保存sheet1.xls”的对话框。判断当前激活的表,并保存这个表。
            MyExcel.DisplayAlerts = false;
            MyExcel.AlertBeforeOverwriting = false;

            MyExcel.ActiveWorkbook.SaveCopyAs(filename);

            MyExcel.Quit();

MSDN中对ApplicationClass.DisplayAlerts 属性的解释是:

The default value is True. Set this property to False if you don’t want to be disturbed by prompts and alert messages while a macro is running; any time a message requires a response, Microsoft Excel chooses the default response.

If you set this property to False, Micorosoft Excel sets this property to True when the code is finished, unless you are running cross process code.

When using the SaveAs method for workbooks to overwrite an existing file, the 'Overwrite' alert has a default of 'No', while the 'Yes' response is selected by Excel when the DisplayAlerts property is set equal to True.

MSDN中对ApplicationClass.AlertBeforeOverwriting 属性的解释是:

True if Microsoft Excel displays a message before overwriting nonblank cells during a drag-and-drop editing operation. Read/write Boolean.

ApplicationClass类实现了接口_Application。MSDN中对_Application.ActiveWorkbook 属性的解释是:

Returns a Workbook object that represents the workbook in the active window (the window on top). Returns Nothing if there are no windows open or if either the Info window or the Clipboard window is the active window.

Workbook类实现了接口_Workbook。MSDN中对_Workbook.SaveCopyAs 方法的定义是:

void SaveCopyAs([In, Optional] object Filename);

解释如下:

Saves a copy of the workbook to a file but doesn't modify the open workbook in memory.

对Filename的解释如下:

Filename

Required. Specifies the file name for the copy.

MSDN中对ApplicationClass.Quit()方法的解释是:

Quits Microsoft Excel.

If unsaved workbooks are open when you use this method, Microsoft Excel displays a dialog box asking whether you want to save the changes. You can prevent this by saving all workbooks before using the Quit method or by setting the DisplayAlerts property to False. When this property is False, Microsoft Excel doesnt display the dialog box when you quit with unsaved workbooks; it quits without saving them.

If you set the Saved property for a workbook to True without saving the workbook to the disk, Microsoft Excel will quit without asking you to save the workbook.

 

转载:http://jangmon.blogbus.com/logs/37880865.html

免责声明:文章转载自《VS2008环境下C#对Excel的操作 [C#] (收集转载)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇原创: SpringBoot配置HTTPS,并实现HTTP访问自动转HTTPS访问vue 手指长按触发事件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C#中对EXCEL保存的SAVEAS方法说明

object missing = System.Reflection.Missing.Value;myWorkbook.SaveAs(fileallpath,Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,missing,missing,missing,missing,Micro...

解决双击excel文件打开多个excel.exe进程的问题

解决双击excel文件打开多个excel.exe进程的问题有些时候,双击两个excel文件,会打开多个excel进程,不同进程之间不能复制粘贴公式,只能粘贴数值,很不方便。怎么样双击多个excel文件只打开一个excel进程呢?1.使用快捷键组合“Win+R”调出运行命令框,键入 regedit.exe,回车,打开注册表编辑器。2.修改HKEY_CLASS...

python(openpyxl)复制excel数据到另一个excel数据表

之前写过https://www.cnblogs.com/pu369/p/15430224.html 代码: #-*- coding: utf-8 -*- fromopenpyxl import Workbook fromopenpyxl import load_workbook import openpyxl #globalitems =[] file1...

如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件

1.描述 PDF文件是一种便携文件格式,是由Adobe公司所开发的独特的跨平台文件格式。PDF文件以PostScript语言图象模型为基础,无论在哪种打印机上都可保证精确的颜色和准确的打印效果,即PDF会忠实地再现原稿的每一个字符、颜色以及图象。可移植文档格式,也称为"便携文档格式",是一种电子文件格式。这种文件格式与操作系统平台无关,也就是说,PDF文件...

Python3读取Excel,日期列读出来是数字的处理

  Python读取Excel,里面如果是日期,直接读出来是float类型,无法直接使用。   通过判断读取表格的数据类型ctype,进一步处理。   返回的单元格内容的类型有5种:   ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error   ctype =sheet1.cell(iR...

Java学习---Excel读写操作

1.1.1. 简介 Apache POI 使用Apache POI 完成Excel读写操作 Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 http://poi.apache.org/ 下载POI的jar包 ,包括以下...