Method for operating Excel in C # (1)

xiaoxiao2021-03-06  90

The first is how to create, open, read, write, and save general code:

Using system; using system.reflection;

Namespace CEXCEL1 {

Class class1 {

[Stathread] static void

Main

(String [] args) {

// Create an Application object Excel.Application XAPP = New Excel.ApplicationClass ();

Xapp.visible = true; // Get the Workbook object, one of two ways: The following is to open existing files Excel.Workbook Xbook = xapp.Workbooks._open (@ "d: /sample.xls", missing . Value, miss, miss, miss, miss, miss, miss, miss.Value, missing.value, missing.value, missing.value, missing.value; // Xbook = xapp.workbooks.add (missing.value); / / New file code // Specify the Sheet you want to operate, two ways:

Excel.Worksheet Xsheet = (Excel.Worksheet) Xbook.sheets [1]; //excel.worksheet xsheet = (Excel.Worksheet) XAPP.Activeesheet; // Read Data, via Range Object Excel.Range RNG1 = xsheet.Get_Range ("A1", TYPE.MISSING; Console.WriteLine (RNG1.Value2); // Read, through the RANGE object, but use different interfaces to get Range Excel.Range RNG2 = (Excel.Range) xsheet.cells [3 , 1]; console.writeLine (RNG2.Value2); // Write data

Excel.Range RNG3 = xsheet.get_range ("c6", missing.value); RNG3.Value2 = "Hello"; RNG3.interior.ColorIndex = 6; // Setting the background color of the Range

// Save mode 1: Save Workbook //xbook.saveas(@"d:/cdata.xls", miss.Value, missing.value, missing.value //, Excel.xlsaveasaccessMode. Xlnochange, missing.value, missing.value, missing.value

////////Iusing.value, missing.value;

// Save mode 2: Save Worksheet //xsheet.saveas(@"d:/cdata2.xls", missing.value, missing.value, missing.value, missing.value

/////Iysing.value, missing.value, missing.value, missing.value, missing.value;

// Save mode three xbook.save ();

XSheet = null; xbook = null; xapp.quit (); // This sentence is very important, otherwise the Excel object cannot withdraw from xapp = null;}}}

转载请注明原文地址:https://www.9cbs.com/read-122786.html

New Post(0)