将数据导入到Excel和Word中

 
导入Excel方法一 :( 该方法要引入两个模板,MyExcel.xls和MyTemplate.xls。要用到office组件。
using Excel;
using System.Diagnostics;
 
// 打印按钮。
 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    // 判断Gridview是否为空。如果是空,则返回。
        if (this.gdviewDeptExecute.Rows.Count <= 0)
        {
            return;
        }
  
       // 定义一个数据集。获得绑定Gridview的值。
        DataSet printDS = new DataSet();
        printDS = car.LoadAffirmInfo(); -- 绑定gridview时调用的方法。
      
       // 定义一个Excel的应用程序。
        Excel.Application oExcel = new Application();
        Workbooks oBooks;
        Workbook oBook;
        Sheets oSheets;
        Worksheet oSheet;
        Range oCells;
 
        // 定义两个字符串。
        string sFile, sTemplate;
        // 定义一个字符串来获取请求应用程序的路径。
        string app = Server.MapPath(Request.ApplicationPath);
        // 新建一个数据表
        System.Data.DataTable dt = printDS.Tables[0];
 
        // 两个字符串所用的Excel的路径。
        sFile = app + "//MyExcel.xls";
        sTemplate = app + "//MyTemplate.xls";
 
        oExcel.Visible = false;
        oExcel.DisplayAlerts = false;
        // 定义一个新的工作簿
        oBooks = oExcel.Workbooks;
        oBooks.Open(sTemplate, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        oBook = oBooks.get_Item(1);
        oSheets = oBook.Worksheets;
        oSheet = (Worksheet)oSheets.get_Item(1);
        // 命名该sheet
        oSheet.Name = "Sheet1";
 
        oCells = oSheet.Cells;
 
        // 调用方法dumpData.
        DumpData(dt, oCells);
 
        // 定义一个工作薄的字体,及字体大小等。
        oSheet.get_Range("A1", "D1").Font.Name = " 宋体" ;
        oSheet.get_Range("A1", "D1").Font.Size = 14;
        oSheet.get_Range("A1", "D1").Borders.LineStyle = 1;
 
        // 保存
        oSheet.SaveAs(sFile, Excel.XlFileFormat.xlTemplate, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
        oBook.Close(false, Type.Missing, Type.Missing);
        // 退出Excel, 并且释放调用的COM资源
        oExcel.Quit();
 
        //
        // 显示下载
        string str = "<script type='text/javascript'>window.open('/Web/MyExcel.xls','','toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=no, status=no');</script>";
        this.RegisterClientScriptBlock(Guid.NewGuid().ToString(), str);
 
        //gridview 的数据源。并将数据进行绑定,gdviewDeptExecute是gridview的ID.
        gdviewDeptExecute.DataSource = printDS;
        gdviewDeptExecute.DataBind();
    }
    // 把Table的数据导入到Excel
    private void DumpData(System.Data.DataTable dt, Excel.Range oCells)
    {
        // 给Excel定位。
        oCells[1, 2] = " 车辆统计列表" ;
        // 先导入表头
        oCells[3, 2] = " 申请部门" ;
        oCells[3, 3] = " 车辆型号" ;
        oCells[3, 4] = " 车牌号" ;
        oCells[3, 5] = " 出发日期" ;
        oCells[3, 6] = " 归还日期" ;
      
        // 再导入表数据
        DataRow dr;
        for (int iRow = 1; iRow < dt.Rows.Count; iRow++)
        {
            dr = dt.Rows[iRow];
            for (int iCol = 1; iCol < dr.ItemArray.Length; iCol++)
            {
                oCells[iRow + 4, iCol + 1] = dr.ItemArray[iCol].ToString();
              
            }
        }
 
       
    }
    private void KillProcess(string processName)
    {
        System.Diagnostics.Process myproc = new System.Diagnostics.Process();
        // 得到所有打开的进程
        try
        {
            foreach (Process thisproc in Process.GetProcessesByName(processName))
            {
                if (!thisproc.CloseMainWindow())
                {
                    thisproc.Kill();
                }
            }
        }
        catch (Exception Exc)
        {
            throw new Exception("", Exc);
        }
}
 
导入Excel方法二:(该方法适用于Excel也适用Word)
using Excel;
using System.Diagnostics;
 
protected void btnExcel_Click(object sender, EventArgs e)
    {
        // 把DataGrid中的数据导出到Excel
        DataSet1 dsGrid = RunDataSet(txtSelect.Text);
        // 如果是将数据导入到Excel中,可以将下面方法的名称设为:.xls 如果要将数据导入到Word中,将文件名改为.Doc即可。 
    CreateExcel(dsGrid, "defExcel.xls");
}
public void CreateExcel(DataSet ds,string FileName)
    {
        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);  
        string colHeaders= "", ls_item="";
        int i=0;
 
        // 定义表对象与行对像,同时用DataSet对其值进行初始化
        DataTable dt=ds.Tables[0];
        DataRow[] myRow=dt.Select("");
 
        // 取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
        for (i = 0; i < dt.Columns.Count-1; i++)
        {
            colHeaders += DataGrid1.Columns[i].HeaderText + "/t";
        }
        colHeaders +=DataGrid1.Columns[i].HeaderText +"/n";
 
        // 向HTTP输出流中写入取得的数据信息
        resp.Write(colHeaders);
        // 逐行处理数据 
        foreach(DataRow row in myRow)
        {
            // 在当前行中,逐列获得数据,数据之间以/t分割,结束时加回车符/n
            for(i=0;i<row.ItemArray.Length-1;i++)
            {
                ls_item +=row[i].ToString() + "/t";
            }
            ls_item += row[i].ToString() +"/n";
            // 当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   
            resp.Write(ls_item);
            ls_item="";
        }
 
        // 写缓冲区中的数据到HTTP头文件中
        resp.End();
    }
// PosID 是界面上的一个文本框值,如果文本框中没有值,查找所有的记录,如果文本框中输入的值 ,将按输入条件进行查找。
// 定义一个数据集。
private DataSet1 RunDataSet(string PosID)
{   
// 建立数据库连接
        SqlConnection conn = new SqlConnection("Server=(local);DataBase=pubs;UID=sa;PWD=");
        // 打开连接;
        conn.Open();
 
        string conStr;
        // 根据传进来的值进行判断,如果值为空:查询所有的数据;如果不为空,将根据传进来的值进行查询数据。
        if (PosID.Length==0)
            conStr = "select d.DeptName, p.PosID, p.PosType, p.PosTelNo, p.PosPlace, case Useflg when 0 then ' 不正常' when 1 then '正常' end as 'UseFlg' from CRPosInfo p, CRDeptInfo d where p.deptID=d.deptID" ;
        else
            conStr = "select d.DeptName, p.PosID, p.PosType, p.PosTelNo, p.PosPlace, case Useflg when 0 then ' 不正常' when 1 then '正常' end as 'UseFlg' from CRPosInfo p, CRDeptInfo d where p.deptID=d.deptID and PosID like '" + PosID + "%'";
 
        SqlDataAdapter da = new SqlDataAdapter(conStr, conn);
        DataSet1 ds = new DataSet1();
        da.Fill(ds, "CRPosInfo");
        conn.Close();
        // 关闭连接,返回数据集。
        return ds;
    }
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值