c# excel sheep 导出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.Collections;
using Microsoft.Office.Interop.Excel;
namespace Common
{
    public class ExcelExportHelper
    {
        /// <summary>
        /// 集合装换DataTable
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static System.Data.DataTable ToDataSet(IList p_List)
        {
            System.Data.DataTable _DataTable = new System.Data.DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);
                }
                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            return _DataTable;
        }
        /// <summary>
        /// 分Sheet导出Excel文件
        /// </summary>
        /// <param name="dv">需导出的DataView</param>
        /// <returns>导出文件的路径</returns>
        /// <summary>
        /// 分Sheet导出Excel文件
        /// </summary>
        /// <param name="ds">需要导出的数据集 可包含多个Table</param>
        /// <param name="fileName">导出的文件名(不能有横线-,也不能有空格)</param>
        /// <returns></returns>
        public static void DataView2ExcelBySheet(string[] SheetName, DataSet ds, string fileName)
        {
            GC.Collect();//垃圾回收
            Application excel;
            _Workbook xBk;
            _Worksheet xSt = null;
            excel = new ApplicationClass();
            xBk = excel.Workbooks.Add(true);
            //定义循环中要使用的变量
            int rowIndex = 0;
            int colIndex = 0;
            int sheetCount = 1;
            //对全部Sheet进行操作
            foreach (System.Data.DataTable dt in ds.Tables)
            {
                //初始化Sheet中的变量
                rowIndex = 1;
                colIndex = 1;
                //创建一个Sheet
                if (null == xSt)
                {
                    xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
                }
                else
                {
                    xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing);
                }
                //设置Sheet的名称
                if (SheetName.Length > 0)
                {
                    xSt.Name = SheetName[sheetCount - 1];
                }
                //取得标题
                foreach (DataColumn col in dt.Columns)
                {
                    //设置标题格式
                    xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter; //设置标题居中对齐
                    xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).Font.Bold = true;//设置标题为粗体
                    //填值,并进行下一列
                    excel.Cells[rowIndex, colIndex++] = col.ColumnName;
                }
                //取得表格中数量
                int drvIndex;
                for (drvIndex = 0; drvIndex <= dt.Rows.Count - 1; drvIndex++)
                {
                    DataRow row = dt.Rows[drvIndex];
                    //新起一行,当前单元格移至行首
                    rowIndex++;
                    colIndex = 1;
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (col.DataType == System.Type.GetType("System.DateTime"))
                        {
                            excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
                        }
                        else if (col.DataType == System.Type.GetType("System.String"))
                        {
                            if (row[col.ColumnName].ToString().Contains("http"))
                            {
                                excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                                Range tempRange = xSt.get_Range(xSt.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]);
                                string strHyperlinks = row[col.ColumnName].ToString();
                                xSt.Hyperlinks.Add(tempRange, strHyperlinks, Missing.Value, Missing.Value, Missing.Value);
                            }
                            else
                            {
                                excel.Cells[rowIndex, colIndex] = "‘" + row[col.ColumnName].ToString();
                            }
                        }
                        else
                        {
                            excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }
                        colIndex++;
                    }
                }
                //使用最佳宽度
                Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex - 1]);
                allDataWithTitleRange.Select();
                allDataWithTitleRange.Columns.AutoFit();
                allDataWithTitleRange.Borders.LineStyle = 1;//将导出Excel加上边框
                sheetCount++;
            }
            //设置导出文件在服务器上的文件夹
            string exportDir = "~/ExcelFile/";//注意:该文件夹您须事先在服务器上建好才行
            string strPath = System.IO.Path.Combine(exportDir, fileName);
            //设置文件在服务器上的路径
            string absFileName = HttpContext.Current.Server.MapPath(exportDir) + fileName;
            xBk.SaveCopyAs(absFileName);
            xBk.Close(false, null, null);
            excel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
            xBk = null;
            excel = null;
            xSt = null;
            GC.Collect();
            HttpResponse resp;
            resp = System.Web.HttpContext.Current.Response;
            resp.Charset = "GB2312";
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
            resp.WriteFile(absFileName, false);
            resp.End();

        }
    }
}
------------------------------
/// <summary>
        /// 文件查询页导出功能
        /// </summary>
        public void SelectDoc_Export2(string data)
        {
            var input = data.DeserializeObject<StructSelectDoc>();
            using (var context = DOCDBHelper.DataContext)
            {
                var results = context.Usp_DOC_SelectDoc_Export(input.docNo, input.docName, input.docFlag,
                    input.docCatagoryID, input.docSenderName, input.docSenderDep, input.docRecvDepName,
                    input.createDate1, input.createDate2);
                List<Usp_DOC_SelectDoc_ExportResult1> revList = results.GetResult<Usp_DOC_SelectDoc_ExportResult1>().ToList();
                List<Usp_DOC_SelectDoc_ExportResult2> sendList = results.GetResult<Usp_DOC_SelectDoc_ExportResult2>().ToList();
                DataSet ds = new DataSet();
                if (revList != null && revList.Count > 0)
                {
                    ds.Tables.Add(CommonUtil.ListToDataTable(revList));
                }
                if (sendList != null && sendList.Count > 0)
                {
                    ds.Tables.Add(CommonUtil.ListToDataTable(sendList));
                }
                if (ds.Tables.Count > 0)
                {
                    string fileName = "DocExport.csv";
                    string[] sheetName = new string[] { "收文", "发文" };
                    ExcelExportHelper.DataView2ExcelBySheet(sheetName, ds, fileName);
                }
            }
        }
时间: 2024-08-10 13:38:18

c# excel sheep 导出的相关文章

使用Apache POI导出Excel小结--导出XLS格式文档

使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI导出Excel小结--导出XLSX格式文档 使用Apache POI导出Excel--大数量导出 导出XLS格式文档 做企业应用项目难免会有数据导出到Excel的需求,最近在使用其,并对导出Excel封装成工具类开放出来供大家参考.关于Apache POI Excel基本的概念与操作我在这里就不啰嗦

Excel导入导出的业务进化场景及组件化的设计方案(转)

1:前言 看过我文章的网友们都知道,通常前言都是我用来打酱油扯点闲情的. 自从写了上面一篇文章之后,领导就找我谈话了,怕我有什么想不开. 所以上一篇的(下)篇,目前先不出来了,哪天我异地二次回忆的时候,再分享分享. 话说最近外面IT行情飞涨还咋的,人都飞哪去了呢,听说各地的军情都进入紧急状态了. 回归下正题,今天就抽点时间,写写技术文,和大伙分享一下近年在框架设计上的取的一些技术成果. 2:项目背景 在针对运营商(移动.联通.电信.铁塔)的信息类的系统中,由于相关的从业人员习惯于Excel的办公

利用反射实现通用的excel导入导出

如果一个项目中存在多种信息的导入导出,为了简化代码,就需要用反射实现通用的excel导入导出 实例代码如下: 1.创建一个 Book类,并编写set和get方法 1 package com.bean; 2 3 public class Book { 4 private int id; 5 private String name; 6 private String type; 7 // public int a; 8 9 public String getType() { 10 System.ou

excel导入导出优化

对于上一篇excel中出现的问题,在excel导入导出中都做了优化.还是eclipse+jdk1.8,但是这个项目是一个web项目,需要配合Tomcat服务器,并且使用了SSH框架, I/O操作过多 首先,对于I/O操作过多,那么就不像之前一样,一条一条的添加或者更新;而且凑齐一堆,也就是一个list集合,然后统一的批量保存. 使用SessionFactory获取当前的session,然后调用session的persist方法,保存实体.只是设置了一个批量的量值.每到30条数据,就将缓存同步到数

thinkphp之Excel的导出

thinkphp之Excel的导出 Excel的导出步骤: 1.下载phpexcel包,置于以下thinkphp框架路径. 内部还有一个文件夹和一个php文件 2.创建excel对象并设置excel对象的属性(ExportALLAction.class.php ); 3.设置excel的行列样式(字体.高宽.颜色.边框.合并等) 4.绘制报表表头 5.将查询数据写入excel 6.设置excel的sheet的名称< 7.设置excel报表打开后初始的sheet 8.设置输出的excel的头参数及

excel的导出和下载

1.前言 有时需要将数据库表资源导出excel,做成一些报表数据. 而php导出excel的方法大致有几种: 使用php的类库,进行导出,如PHPExcel 使用php原生的方法进行导出 而本文介绍的就是,如何通过原生方法导出excel 2.关键函数 2.1.ob输出 ob_start(); ob_get_contents ob_end_clean fopen fwrite fclose iconv 2.2.header输出 header iconv 3.使用ob函数进行excel到导出 ob函

c# 生成excel并导出

用c#的NPOI读写Excel 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 3.POI读取Excel有两种格式一个是HSSF,另一个是XSSF. HSSF和XSSF的区别如下: HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file for

POI实现excel导入导出

1.分析excel import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.Ce

php excel文件导出之phpExcel扩展库

php Excel  文件导出 phpExcel 官网 http://phpexcel.codeplex.com/ /** * 导出特定文件 * 根据具体情况而定 */ public function download(){ //1. 从数据库来获取对应的二维数组 $alist = array(...); $list = $alist; $data = array(); //2. 设置xls的 表头名 $headArr = array("排名","姓名","