asp.net操作excel 代码

using Excel;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;

public class PrintEnXsl
{
    public PrintEnXsl()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    public static string TempEnXsl;

    public bool ProduceXsl(string ItemName)
    {//生成英文成绩单
        Excel.Application oExcel;//= new Excel.Application();
        Excel.Workbooks oBooks;
        Excel.Workbook oBook;
        Excel.Sheets oSheets;

        try
        {
            SqlConnection con = DB.createConnection();
            con.Open();
            //查找该学生基本信息
            string mysql = "select * from tbEmailsMessage where ItemName='" + ItemName + "' and state=5";
            //string mysqlScore = "select * from tbStuScores where StuId='" + StuId + "'";
            SqlDataAdapter da = new SqlDataAdapter(mysql, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();

            //table[0] 成绩信息,table[1]个人信息
            System.Data.DataTable dt = ds.Tables[0];//

            if (dt.Rows.Count > 0)
            {
               //初始化 excel
                oExcel = new Application();
                if (oExcel == null)
                {
                    return false;
                    //Response.Write("<script>alert('不能初始化Excel应用程序!')</script>");
                }
                else
                {
                    string sFile, sTemplate;
                    sFile = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "//Temp//" + HttpContext.Current.Session["UserName"] + "En.xls";
                    sTemplate = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "//TemplateXsl//Template.xls";

                    HttpContext.Current.Session["FilePath"] = "Temp/" + HttpContext.Current.Session["UserName"] + "En.xls";
                    //TempChXsl = sFile;
                    //HttpContext.Current.Session["FilePath"] = sFile;
                    //是否可见,调试时 可以为 true
                    //oExcel.Visible = true;
                    //oExcel.DisplayAlerts = true;
                    oExcel.Visible = false;
                    oExcel.DisplayAlerts = false;

                    if (File.Exists(sFile))
                    {//判断临时文件是否存在,是就删除
                        File.Delete(sFile);
                    }
                    //
                    oBooks = oExcel.Workbooks;
                    oBooks.Add(sTemplate);//打开模板工作簿
                    oBook = oBooks.get_Item(1);

                    //
                    oSheets = oBook.Worksheets;
                    DumpData(ds, oSheets);
                    oBook.SaveAs(sFile, Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
                                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                    oExcel.Quit();

                    //File.Delete(sFile);//删除临时文件
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheets);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);

                    return true;
                }           
            }
            else
            {
                return false;
            }
        }
        catch (SqlException sqlerror)
        {
            HttpContext.Current.Response.Redirect("ErrorPage.aspx?Err=" + sqlerror.Message.Replace("/n", ""), true);
            return false;
        }
        catch (Exception e1)
        {
            //Response.Redirect("ErrorPage.aspx?Err='" + Server.UrlEncode(e1.Message)+"'");
            HttpContext.Current.Response.Redirect("ErrorPage.aspx?Err=" + e1.Message.Replace("/n", ""), true);
            return false;
        }
        finally
        {
            oExcel = null;
            oBooks = null;
            oBook = null;
            oSheets = null;
            System.GC.Collect();

        }
        //return false;
    }

    private void DumpData(DataSet ds, Excel.Sheets oSheets)
    {
        try
        {
            Worksheet oSheetEn;
            Excel.Range oCellsEn;

            //string sFile = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "//Temp//MyExcel.xls";

            System.Data.DataTable dt = ds.Tables[0];//信息           
            oSheetEn = (Excel.Worksheet)oSheets.get_Item(1);//模板

            oSheetEn.Name = "FirstEn";
            oCellsEn = oSheetEn.Cells;

            int j = 3;
            oCellsEn[1, 1] ="项目名:"+dt.Rows[0]["ItemName"].ToString();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                oCellsEn[j, 1] = "问题 " + i + ":" + dt.Rows[i]["QuestionName"].ToString();
                oCellsEn[j, 2] = dt.Rows[i]["QuestionContent"].ToString();
                oCellsEn[j, 3] ="答 :"+ dt.Rows[i]["Answers"].ToString();
                j = j + 2;
            }
            //oCells[i + BeginRow, BeginCol] = StuCurEnName.Substring(0, 21);
            //dumpPublicEn(oCellsEn, dtBasic);
            //this.DumpScoresFourEn(dtScore, length, oCellsEn, startYear);//英文

            System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheetEn);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oCellsEn);

            oSheetEn = null;
            oCellsEn = null;
        }
        finally
        {

        }
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值