频道栏目
首页 > 资讯 > C# > 正文

c#写入数据到excel中的方法2(代码实例)

17-12-11        来源:[db:作者]  
收藏   我要投稿

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 + " 创建完毕!");
        }
相关TAG标签
上一篇:Java代码注释规范讲解
下一篇:Java开发中字符编码的问题(代码实例)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站