c#写入数据到excel中的方法2(代码实例)
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
//方法二,只能创建新文件,不能在原有的文件基础上写入
public static void write2()
{
string path = @"D:\Excel1.xlsx";
//Excel应用程序变量 ,初始化
Application excelApp = new ApplicationClass();
//判断文件是否存在,如果已存在,则删除
if (File.Exists(path))
{
File.Delete(path);
}
//由于使用的是COM库,因此有许多变量需要用Nothing代替
Object Nothing = Missing.Value;
//Excel文档变量
Workbook excelDoc = excelApp.Workbooks.Add(Nothing);
//使用第一个工作表作为插入数据的工作表
Worksheet ws = (Worksheet)excelDoc.Sheets[1];
//声明一个MSExcel.Range 类型的变量r
Range r;
//第一行为字段名,如给a1天假数据,其实数据添加在a2单元格中
//获得a2表格并赋值
//r = ws.get_Range("A1");
//r.Value2 = "数据1";
//获得d5至a2处的表格,并赋值
r = ws.get_Range("d4", "a1");
r.Value2 = "5.7";
//删除该范围的数据
//r.Delete();
//插入该范围内的行列单元格
r.Insert();
//WdSaveFormat为Excel文档的保存格式
object format = XlFileFormat.xlWorkbookDefault;
//将excelDoc文档对象的内容保存为XLSX文档
excelDoc.SaveAs(path, format, Nothing, Nothing, Nothing, Nothing, XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
//关闭excelDoc文档对象
excelDoc.Close(Nothing, Nothing, Nothing);
//关闭excelApp组件对象
excelApp.Quit();
Console.WriteLine(path + " 创建完毕!");
}