Using Excel in C #

Source: Internet
Author: User

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Reflection;
Using System.Runtime.InteropServices;
Using Microsoft.Office.Interop.Excel;
Using excelapplication = Microsoft.Office.Interop.Excel.ApplicationClass;

Namespace Excaldemo
{
public class EXCELFiles
{
public void Createexcelfiles ()
{
Create an instance of Excel
ExcelApplication Excel = new ExcelApplication ();
Try
{
The commented out statement is: Open an Excel file from the specified location on the disk
Excel. Workbooks.Open ("Demo.xls", Missing.Value, Missing.Value,
Missing.value,missing.value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Excel. Visible = false;//does not display Excel files and if True displays Excel files
Excel. Workbooks.Add (Missing.Value);//Add workbooks
Worksheet sheet = (Worksheet) Excel. activesheet;//getting the current worksheet

Range range = null;//creates an empty cell object
Sheet.get_range (sheet. Cells[29,2],sheet. cells[29,2]). orientation=excel.xlorientation.xlvertical;//font is centered vertically in the cell then cell

Range = Sheet.get_range ("A1", Missing.Value);//Get a single cell
Range.           RowHeight = 20; Set row height
Range.         ColumnWidth = 20; Set column widths
Range.    Borders.LineStyle = 1; Set cell borders
Range.         Font.Bold = true; Bold font
Range.           Font.Size = 20; Set Font size
Range.      Font.ColorIndex = 5; Set Font Color
Range.  Interior.ColorIndex = 6; Set cell background color
Range. HorizontalAlignment = xlhalign.xlhaligncenter;//Set cell to center horizontally
Range. VerticalAlignment = xlvalign.xlvaligncenter;//Set cell vertically centered
Range. Value2 = "Set row height and column width";//Set cell value


Range = Sheet.get_range ("B2", "D4");//Get multiple cells
Range.         Merge (Missing.Value); Merge cells
Range.            Columns.AutoFit (); Set column width to auto fit
Range. numberformatlocal = "#,# #0.00";//Set cell format to currency format
Set the left border of the cell bold
Range. Borders[xlbordersindex.xledgeleft]. Weight = Xlborderweight.xlthick;
Set cell right Border bold
Range. Borders[xlbordersindex.xledgeright]. Weight = Xlborderweight.xlthick;
Range. Value2 = "merged cells";

Page Setup
Sheet.          Pagesetup.papersize = XLPAPERSIZE.XLPAPERA4; Set Page size to A4
Sheet. Pagesetup.orientation = xlpageorientation.xlportrait; Set Vertical layout
Sheet.                         Pagesetup.headermargin = 0.0; Set the header margin
Sheet.                         Pagesetup.footermargin = 0.0; Set footer margins
Sheet. PageSetup.LeftMargin = Excel. InchesToPoints (0.354330708661417); Set the left margin
Sheet. Pagesetup.rightmargin = Excel. InchesToPoints (0.354330708661417);//Set Right margin
Sheet. Pagesetup.topmargin = Excel.  InchesToPoints (0.393700787401575); Set Top margin
Sheet. Pagesetup.bottommargin = Excel. InchesToPoints (0.393700787401575);//Set Bottom margin
Sheet.                  Pagesetup.centerhorizontally = true; Set Horizontal Center

                //  Print file
                 sheet. PrintOut (Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                
                 //  save file to program run directory
                 Sheet. SaveAs (system.windows.forms.application.startuppath +  "\demo.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Excel. Activeworkbook.close (false, NULL, NULL); Close the Excel file without saving
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}
Finally
{
Excel. Quit (); Exit Excel
Excel = null; Set an instance of Excel to be empty
Even then, you can still see an Excel process in the System Task Manager, but sometimes you don't see
This is a Bug for Office 2003, according to non-authoritative personnel. This question needs to be researched.
}
}
}
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}
Finally
{
Excel. Quit (); Exit Excel
Excel = null; Set an instance of Excel to be empty
Even then, you can still see an Excel process in the System Task Manager, but sometimes you don't see
This is a Bug for Office 2003, according to non-authoritative personnel. This question needs to be researched.
}
}
}
}


Range = Sheet.get_range ("B2", "D4");//Get multiple cells
Range.         Merge (Missing.Value); Merge cells
Range.            Columns.AutoFit (); Set column width to auto fit
Range. numberformatlocal = "#,# #0.00";//Set cell format to currency format
Set the left border of the cell bold
Range. Borders[xlbordersindex.xledgeleft]. Weight = Xlborderweight.xlthick;
Set cell right Border bold
Range. Borders[xlbordersindex.xledgeright]. Weight = Xlborderweight.xlthick;
Range. Value2 = "merged cells";

Page Setup
Sheet.          Pagesetup.papersize = XLPAPERSIZE.XLPAPERA4; Set Page size to A4
Sheet. Pagesetup.orientation = xlpageorientation.xlportrait; Set Vertical layout
Sheet.                         Pagesetup.headermargin = 0.0; Set the header margin
Sheet.                         Pagesetup.footermargin = 0.0; Set footer margins
Sheet. PageSetup.LeftMargin = Excel. InchesToPoints (0.354330708661417); Set the left margin
Sheet. Pagesetup.rightmargin = Excel. InchesToPoints (0.354330708661417);//Set Right margin
Sheet. Pagesetup.topmargin = Excel.  InchesToPoints (0.393700787401575); Set Top margin
Sheet. Pagesetup.bottommargin = Excel. InchesToPoints (0.393700787401575);//Set Bottom margin
                 sheet. pagesetup.centerhorizontally = true;                   //  Set Horizontal Center

                //  Print file
                 sheet. PrintOut (Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                
                 //  save file to program run directory
                 Sheet. SaveAs (system.windows.forms.application.startuppath +  "\demo.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Excel. Activeworkbook.close (false, NULL, NULL); Close the Excel file without saving
}

Running environment: Microsoft Office Excel 2003 + Microsoft Visual Studio 2005

1. Adding a reference to a COM component for a project
Here's how:
Item, add Reference, COM, Microsoft Excel object 11.0 Object Library--OK
At this point, 3 references are added to the project: Excel, Microsoft.Office.Core, vbide

2. In the class file, add a reference to the following namespace
Using System.Reflection;
Using System.Runtime.InteropServices;
Using Microsoft.Office.Interop.Excel;

Using excelapplication = Microsoft.Office.Interop.Excel.ApplicationClass; In order to distinguish it from the application class under the System.Windows.Forms namespace, it is purely convenient to write code.

Note: It is best not to use it in a form class. Because, when the Microsoft.Office.Interop.Excel namespace is introduced, the application interface under the Microsoft.Office.Interop.Excel namespace is in conjunction with the The application class under the System.Windows.Forms namespace generates ambiguity conflicts. To use the application class, you must add the full namespace name before application.

You can use Excel with the above 2 steps. However, MSDN for Excel is rare and most are Chinese. This is inconvenient for using Excel. It is difficult to resize a cell. Here I tell you a simple and practical stupid method. That's it: Open your Excel and record the macro. Then, according to the generated VB code, go to MSDN to check the relevant C # Help.

Using Excel in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.