不使用模板导出Excel(C#版本)

不多说,直接上干货!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Web.Services.Protocols;

using Paims.Server.Business;
using Paims.Server.Business.Common;

using Paims.Server.UI;
using Paims.Server.UI.HttpExtension;

using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.Data.Common;
using System.Data.OleDb;

using Paims.Website.Service.WordHelpers;

using Microsoft.Office.Interop.Excel;

using System.Windows.Forms;

using System.Web.UI;
using System.Web.UI.HtmlControls;


using MIS.Common.Exceptions;

namespace Paims.WebSite.Service.Export
{
    /// <summary>
    /// ExportExpertWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class ExportExpertWebService : WebServiceBase
    {

        [WebMethod]
        public string Exportexpert()
        {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            object missing = System.Reflection.Missing.Value;
            object Visible = false;
            object ReadOnly = false;

            Microsoft.Office.Interop.Excel._Workbook myWorkbook;            //工作薄实例声明
            Microsoft.Office.Interop.Excel._Worksheet myWorksheet;          //工作表实例声明
            excel.Application.Workbooks.Add(true);              //不存在相同文件,则建立一个新的文件
            myWorkbook = excel.ActiveWorkbook;                  //工作薄赋值为excel中的已激活工作薄
            myWorksheet = (Microsoft.Office.Interop.Excel._Worksheet)myWorkbook.ActiveSheet;    //工作表赋值为工作簿中已激活的工作表
            string[] IDStrings = {"123","234","123","234","123","234","123","234"};
            //获取数据库中的行数,并将其保存到excel中
            for (int i = 0; i < 7; i++)
            {
                myWorksheet.Cells[i + 2, 1] = IDStrings[i].ToString();
               
            }
            myWorksheet.Name = "sheetTest";         //给工作表取名字
            //将工作簿另存为
            myWorkbook.SaveAs(@"D:	est5.xlsx", missing, missing, missing, missing, missing,
     Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing , missing, missing);
            myWorkbook.Close(null, null, null);                 //关闭工作簿
            excel.Quit();                                       //退出excel
            excel = null;                                       //赋值为NULL
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/Eaglery/p/4023734.html