導出文件到excel

本文提供兩種導入數據到excel 中

1.從數據庫查出數據 保存到實體中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using klzx.NoteFlatrootSys.BLL;
using klzx.NoteFlatrootSys.Model;

/// <summary>
///ExportToExcel 的摘要說明
/// </summary>
public class ExportToExcel
{
    public ExportToExcel()
    {
        //
        //TODO: 在此處添加構造函數邏輯
        //
    }
      [Dependency]
    public Iview_smsphone_smsjobBLL v_smsphone_smsjobbll { get; set; }
      public static void ToExcel(List<SMSPhone> smsphonelist)  //房間導入到excel 方法
    {
        Excel.Application excel1 = new Excel.Application();
       
        excel1.Application.Workbooks.Add(true);
        excel1.Visible = true;
        //填充表頭電話id
        excel1.Cells[1, 1] = "電話id ";
        excel1.Cells[1, 2] = "任務id";
        excel1.Cells[1, 3] = "電話號碼";
        excel1.Cells[1, 4] = "反饋時間";
        excel1.Cells[1, 5] = "反饋狀態";
 
        //填充數據
        for (int i = 0, j = 0; i < smsphonelist.Count; i++, j++)
        {
            excel1.Cells[i + 2, 1] = smsphonelist[i].PhoneID.ToString();
            excel1.Cells[i + 2, 2] = smsphonelist[i].JobID.ToString();
            excel1.Cells[i + 2, 3] = smsphonelist[i].Phone.ToString();
            excel1.Cells[i + 2, 4] = smsphonelist[i].FDate.ToString();
            excel1.Cells[i + 2, 5] = smsphonelist[i].Status.ToString();       
        }
    }
   
}

2. 從gridview 中讀取數據導入到excel  中

  protected void Button1_Click(object sender, EventArgs e)
    {
        ExportToExcel("application/ms-excel", "贏利大幅度提高統計.xls");

    }
    //將數據導入到Excel 中
    public void ExportToExcel(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        //將http流添加到數據流
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);// 將控件內容寫到服務器控件流中
        Response.Write(tw.ToString());
        Response.End();

    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }

發佈了49 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章