C# 如何在一个已经存在的EXCEL里写入数据

C# 怎么在一个已经存在的EXCEL里写入数据?
C#   怎么在一个已经存在的EXCEL里写入数据?

------解决方案--------------------
首先是如何创建、打开、读取、写入、保存的一般性代码:


using System;
using System.Reflection; // 引用这个才能使用Missing字段

namespace CExcel1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
//创建Application对象
Excel.Application xApp=new Excel.ApplicationClass();

xApp.Visible=true;
//得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件
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);//新建文件的代码
//指定要操作的Sheet,两种方式:

Excel.Worksheet xSheet=(Excel.Worksheet)xBook.Sheets[1];
//Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet;

//读取数据,通过Range对象
Excel.Range rng1=xSheet.get_Range( "A1 ",Type.Missing);
Console.WriteLine(rng1.Value2);

//读取,通过Range对象,但使用不同的接口得到Range
Excel.Range rng2=(Excel.Range)xSheet.Cells[3,1];
Console.WriteLine(rng2.Value2);

//写入数据
Excel.Range rng3=xSheet.get_Range( "C6 ",Missing.Value);
rng3.Value2= "Hello ";
rng3.Interior.ColorIndex=6; //设置Range的背景色

//保存方式一:保存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);

//保存方式二:保存WorkSheet
xSheet.SaveAs(@ "D:\CData2.xls ",
Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);


//保存方式三
xBook.Save();

xSheet=null;
xBook=null;
xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
xApp=null;
}
}
}


------解决方案--------------------
下面是我以前写的一个测试,以xml方式扣作excel,很方便但缺点是只有0ffice 2003才能打开这样的xls文件.......

第一步先建一个excel模板文件(以xml格式另存为test.xml)
<?xml version= "1.0 "?>
<?mso-application progid= "Excel.Sheet "?>
<Workbook xmlns= "urn:schemas-microsoft-com:office:spreadsheet "
xmlns:o= "urn:schemas-microsoft-com:office:office "
xmlns:x= "urn:schemas-microsoft-com:office:excel "
xmlns:ss= "urn:schemas-microsoft-com:office:spreadsheet "
xmlns:html= "http://www.w3.org/TR/REC-html40 ">
<DocumentProperties xmlns= "urn:schemas-microsoft-com:office:office ">
<Created> 1996-12-17T01:32:42Z </Created>
<LastSaved> 2007-04-11T01:31:33Z </LastSaved>
<Version> 11.6568 </Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns= "urn:schemas-microsoft-com:office:office ">
<RemovePersonalInformation/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns= "urn:schemas-microsoft-com:office:excel ">