Ways to manipulate Excel in C # (i)

Source: Internet
Author: User
Tags range
Excel is the first way to create, open, read, write, and save general Code:

Using System;
Using System.Reflection;

Namespace CExcel1
{

Class Class1
{

[STAThread]
static void Main (string[] args)
{

Creating application objects
Excel.Application xapp=new Excel.applicationclass ();

Xapp.visible=true;
You can get the workbook object in one of two ways: The following is to open an existing file
Excel.Workbook Xbook=xapp.workbooks._open (@ "D:\Sample.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);
Xbook=xapp.workbooks.add (Missing.Value);//New file code
Specify the sheet to be manipulated in two ways:

Excel.Worksheet xsheet= (Excel.Worksheet) xbook.sheets[1];
Excel.Worksheet xsheet= (Excel.Worksheet) Xapp.activesheet;
Reading data by using the Range object
Excel.Range rng1=xsheet.get_range ("A1", Type.Missing);
Console.WriteLine (rng1. Value2);
Read, through the Range object, but using a different interface 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; Set the background color of a range

Save Way One: Save workbook
Xbook.saveas (@ "D:\CData.xls", Missing.value,missing.value,missing.value,missing.value,missing.value
, Excel.xlsaveasaccessmode.xlnochange,missing.value,missing.value,missing.value

, Missing.value,missing.value);

Save mode Two: Save worksheet
Xsheet.saveas (@ "D:\CData2.xls", Missing.value,missing.value,missing.value,missing.value

, Missing.value,missing.value,missing.value,missing.value,missing.value);

Save Way Three
Xbook.save ();

Xsheet=null;
Xbook=null;
Xapp.quit (); This sentence is very important, otherwise Excel objects cannot exit from memory
Xapp=null;
}

}
}




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.