C#操作excel文件

来源:互联网 发布:网络正规赚钱项目 编辑:程序博客网 时间:2024/05/22 16:23

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Excel = Microsoft.Office.Interop.Excel;using System.IO;using System.Data;namespace ConsoleApplication1{    class Program    {                static void Main(string[] args)        {            Excel.Application app = null;            Excel.Workbooks wbs;             Excel.Workbook wb;             Excel.Worksheet worksheet;             try            {                app = new Excel.Application();//获取exe程序启动路径                string path = AppDomain.CurrentDomain.BaseDirectory;                string excelName = path + "file.xls";                string saveFile = path + "TicketModule";                wbs = app.Workbooks; //加载excel文档                wb = wbs.Add(excelName);                //设置禁止弹出保存和覆盖的询问提示框                                app.DisplayAlerts = false;                                app.AlertBeforeOverwriting = false;                app.UserControl = true;          //获取第一个sheet                worksheet = (Excel.Worksheet)wb.Worksheets[1];//修改第一行第一列的数据为"hello"                worksheet.Cells[ 1, 1] = "hello";                //wb.Save();                //另存为                object MissingValue = Type.Missing;                wb.SaveAs(saveFile, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue,                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, MissingValue, MissingValue, MissingValue, MissingValue, MissingValue);                app.Quit();            }            catch (System.Exception ex)            {                if (app != null)                {                    app.Quit();                }            }                   }    }}