Excle导出

将数据集中的数据导出到Excle中
  首先需要了解一下excle对象的相关方法,application,workbooks,workbook,range对象,网上有好多介绍的。
  了解了这几个对象后就开始导入导出了,我自己总结了两种方法导出数据集中(such as datatable)的内容。第一种方式是利用response不端的向客户端写datatable中的内容,只需要给response增加一个header就可以了,那你写的所有数据流都是可以放到excle中,直接贴代码咯:
 Response.Clear();
        DataCollections dc = DataCollections.getDataCollection();
        Response.AppendHeader("Content-Disposition", "attachment;filename=notexcelObj.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        Response.ContentType = "application/ms-excel";
        Response.Write("机型"); Response.Write("\t");/*跳到下一个制表格*/ Response.Write("机型号"); Response.Write("\r\n");
        foreach (DataRow item in dc.Rows)
        {
            Response.Write(item[0].ToString());
            Response.Write("\t");
            Response.Write(item[1].ToString());
            Response.Write("\r\n");
        }
        Response.End();
不断遍历数据集输出到Excel,这种方式效率还是比较快的,但是不够灵活,比如要给某一个单元格加批注好像就做不了了。
第二种方式是用excel对象,个人感觉这种方式微软做的还不太好,excel对象在退出后还是杀不了excel这个进程,网上有好多解决的方案,可以搜一下。并且excel这个方式效率还是比较慢的,不过操作灵活,可以控制每一个单元格的属性和方法。
我没有想到过怎么样将excel内容直接输出到客户端,现在是先写了excel文件保存到本地,然后将excel文件输出到客户端同时删除该exce文件,如果有更好的方法,希望大家多多指教。
---输出excel表
object objReflector=System.Reflection.Missing.Value;
        Excel.Application appExcel = null;
        Excel.Workbook workBook = null;
        try
        {
            string tempFilePath = Server.MapPath("~") + " \\temp\\" + Guid.NewGuid().ToString() + ".xls";
            Excel.Sheets sheets = initExcelObj(ref appExcel,ref workBook);
            Excel.Worksheet workSheet = (Excel.Worksheet)sheets.get_Item(1);
            operationExcelObj(workSheet, DataCollections.getDataCollection());
            workBook.SaveAs(tempFilePath, Excel.XlFileFormat.xlXMLSpreadsheet, objReflector, objReflector, false, false,
                Excel.XlSaveAsAccessMode.xlNoChange, objReflector, objReflector, objReflector, objReflector, objReflector);
            appExcel.Workbooks.Close();
            exportExcelToClient(tempFilePath);
            deleteTempExcel(tempFilePath);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            if (appExcel != null)
            {
                appExcel.Workbooks.Close();
                appExcel.Quit();
                appExcel = null;
                GC.Collect(2, GCCollectionMode.Forced);
            }
        }
/// <summary>
    /// 数据集写excel表
    /// </summary>
    /// <param name="?"></param>
    private void operationExcelObj(Excel.Worksheet workSheet,DataCollections dc)
    {
        workSheet.Name = "ldlovewf";
        workSheet.Cells["1", columnA] = "数码品牌";
        workSheet.Cells["1",columnB] = "数码描述";
        for (int i = 0,j=2; i < dc.Rows.Count; i++,j++)
        {
            for(int k=0;k<dc.Columns.Count;k++)
            {
                if (k % 2 == 0)
                    workSheet.Cells[j.ToString(), columnA] = dc.Rows[i][k].ToString();
                else
                    workSheet.Cells[j.ToString(), columnB] = dc.Rows[i][k].ToString();
            }
        }
    }
/// <summary>
    /// 初始化excel对象
    /// </summary>
    /// <param name="appExcel"></param>
    /// <returns></returns>
    private Excel.Sheets initExcelObj(ref Excel.Application appExcel, ref Excel.Workbook workBook)
    {
        appExcel = new Excel.ApplicationClass();
        //appExcel.Visible = true;
        Excel.Workbooks workBooks = appExcel.Workbooks;
        workBook = workBooks.Add(System.Reflection.Missing.Value);
        Excel.Sheets sheets = workBook.Worksheets;
        return sheets;
    }
--读取临时的excel表,输出到客户端
private void exportExcelToClient(string filePath)
    {
        Response.Clear();
        Response.AppendHeader("Content-Disposition", "attachment;filename=notexcelObj.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        Response.Buffer = true;
        Response.WriteFile(filePath);
        Response.End();
    }
--删除临时excel表
 private void deleteTempExcel(string filePath)
    {
        if (System.IO.File.Exists(filePath))
        {
            System.IO.File.Delete(filePath);
        }
    }
这种方式比较繁琐,待续,以后研究一下有没有更好的方法。

你可能感兴趣的:(职场,休闲,Excle导出)