http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 5841|回复: 7

[求助] 怎么能够批量导出EXCEL

[复制链接]
发表于 2016-12-19 09:59:08 | 显示全部楼层 |阅读模式
  1.这里加了判断,行数每超过60000行,就多导出一个excel
  
[C#] 纯文本查看 复制代码
#region public static void ExportExcel(string, DataSet, string) 根据模板配置文件,导出装载好数据后的Excel文件。
    /// <summary>
    /// 根据模板配置文件,导出装载好数据后的Excel文件。
    /// </summary>
    /// <param name="p_XmlName">Xml配置文件名。</param>
    /// <param name="p_DataSet">数据源对象。</param>
    /// <param name="p_ExportName">导出的Excel文件名。</param>
    public static void ExportExcel(string p_XmlName, DataSet p_DataSet, string p_ExportName)
    {
        int maxrowcount = 300;
        double decexcelcount = 1;
        foreach (DotNetTable dt in p_DataSet.Tables)
        {
            double maxcount = Math.Ceiling(dt.Rows.Count * 1.0 / maxrowcount);
            if (maxcount > decexcelcount)
                decexcelcount = maxcount;
        }
        if (decexcelcount > 1)
        {
            for (int i = 0; i < decexcelcount; i++)
            {
                foreach (DotNetTable dt in p_DataSet.Tables)
                {
                    DataSet ds_new = new DataSet();
                    double maxcount = Math.Ceiling(dt.Rows.Count * 1.0 / maxrowcount);
                    if (maxcount == 1.0)
                    {
                        DotNetTable dt_new = dt.Clone();
                        ds_new.Tables.Add(dt_new);
                    }
                    else
                    {
                        DotNetTable dt_new = new DotNetTable(dt.TableName);
                        dt_new = dt.Clone();
                        dt_new.Rows.Clear();
                        int remainrowscount = dt.Rows.Count - i * maxrowcount;
                        if (remainrowscount > maxrowcount)
                            remainrowscount = maxrowcount;

                        for (int j = 0; j < remainrowscount; j++)
                        {
                            DataRow dr_new = dt.Rows[i * maxrowcount + j];
                            dt_new.Rows.Add(dr_new.ItemArray);
                        }
                        ds_new.Tables.Add(dt_new);
                    }
                }
                ExportExcel(p_XmlName, p_DataSet, p_ExportName + "_" + (i + 1).ToString(), "");
            }
        }
        else
        {
            ExportExcel(p_XmlName, p_DataSet, p_ExportName, "");
        }

    }

    #endregion
2.用模版导出excel
    #region public static void ExportExcel(string, DataSet, string) 根据模板配置文件,导出装载好数据后的Excel文件。
    /// <summary>
    /// 根据模板配置文件,导出装载好数据后的Excel文件。
    /// </summary>
    /// <param name="p_XmlName">Xml配置文件名。</param>
    /// <param name="p_DataSet">数据源对象。</param>
    /// <param name="p_ExportName">导出的Excel文件名。</param>
    public static void ExportExcel(string p_XmlName, DataSet p_DataSet, string p_ExportName, string strmore)
    {

      KillExcel();
      _Application xApplication = null;
      string sBookPathT = null;
      try {
        //初始化Excel模板对象
        string sRootPath1 = string.Format(@"{0}\", HttpContext.Current.Server.MapPath("~/") + TFLConstants.Cfg_XmlTempURL);
        string sRootPath2 = string.Format(@"{0}\", HttpContext.Current.Server.MapPath("~/") + TFLConstants.Cfg_TempFileFolderName);
        if (!Directory.Exists(sRootPath2)) {
          Directory.CreateDirectory(sRootPath2);
        }
        //删除该目录下超过180天的临时文件
        try {
          DirectoryInfo dirInfo = new DirectoryInfo(sRootPath2);
          foreach (FileInfo tFile in dirInfo.GetFiles()) {
            if ((DateTime.Now.Date - tFile.CreationTime).TotalDays > 180) {
              tFile.Delete();
            }
          }
        } catch {
        }
        string sXmlPath = string.Format("{0}{1}.xml", sRootPath1, p_XmlName);//Xml配置文件全路径
        ExcelSchema schema = GetExcelSchema(sXmlPath);
        string sBookPathS = string.Format("{0}{1}.xls", sRootPath1, schema.XlsFile);//模板文件全路径
        sBookPathT = string.Format("{0}{1}{2}.xls", sRootPath2, DateTime.Now.ToString("yyyyMMddHHmmss"), schema.XlsFile);
        //Excel应用程序初始化
        xApplication = new ApplicationClass();
        xApplication.Visible = true;
        xApplication.DisplayAlerts = false;
        //装载模板文件,另存为新的文件
        Workbook xWorkBook = xApplication.Workbooks.Add(sBookPathS);
        xWorkBook.SaveAs(sBookPathT, _MValue, _MValue, _MValue, _MValue, _MValue, XlSaveAsAccessMode.xlNoChange, _MValue, _MValue, _MValue, _MValue, _MValue);
        //创建原始数据Sheet
        foreach (DotNetTable dt in p_DataSet.Tables) {
          foreach (WSheet sheet in schema.WSheets) {
            if (sheet.TableName == dt.TableName && dt.Rows.Count > 0) {
              //填充数据
              Worksheet xWorkSheet = xWorkBook.Worksheets[string.IsNullOrEmpty(sheet.SheetName) ? sheet.TableName : sheet.SheetName] as Worksheet;
              int iRowCount = dt.Rows.Count;
              int iColumnCount = dt.Columns.Count;
              object[,] objs = new object[iRowCount, iColumnCount];
              for (int i = 0; i < iRowCount; i++) {
                for (int j = 0; j < iColumnCount; j++) {
                  objs[i, j] = dt.Rows[j];
                }
              }
              xWorkSheet.get_Range(xWorkSheet.Cells[1, 1], xWorkSheet.Cells[iRowCount, iColumnCount]).Value2 = objs;
              break;
            }
          }
        }
        //运行宏
        if (!string.IsNullOrEmpty(schema.MacroName)) {
          xApplication.Run(schema.MacroName, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue,
            _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue,
            _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue, _MValue);
        }
        //删除宏模块
        List<string> ModuleList;
        if (string.IsNullOrEmpty(schema.ModuleNames)) {
          ModuleList = new List<string>();
        } else {
          ModuleList = new List<string>(schema.ModuleNames.Split(new char[] { ',' }));
        }
        foreach (VBComponent macro in xWorkBook.VBProject.VBComponents) {
          if (macro.Type == vbext_ComponentType.vbext_ct_StdModule || macro.Type == vbext_ComponentType.vbext_ct_ClassModule) {
            if (!ModuleList.Contains(macro.Name)) {
              xWorkBook.VBProject.VBComponents.Remove(macro);
            }
          }
        }
        //保存改变,销毁资源
        xWorkBook.Save();

        try {
          xWorkBook.Close(null, null, null);
          xApplication.Workbooks.Close();
          xApplication.Quit();
        } catch {
          KillExcel(xApplication);
        }

        //Marshal.ReleaseComObject(xWorkBook);
        //Marshal.ReleaseComObject(xApplication);
        //xApplication = null;
        //GC.Collect();

        //导出Excel文件,并删除临时文件
        p_ExportName = string.Format("{0}.xls", string.IsNullOrEmpty(p_ExportName) ? schema.XlsFile : p_ExportName);
        ResponseHelp.ResponseFile(p_ExportName, En_ResponseType.Excel, sBookPathT);
      } finally {
        try {
          if (File.Exists(sBookPathT)) {
            File.Delete(sBookPathT);
          }
        } catch { }
        KillExcel(xApplication);
      }
    }
    #endregion

3.导出excel

  #region private static void ResponseToClient(string, En_ResponseType, string, bool) 将服务器端文件以流的方式响应给客户端。
    /// <summary>
    /// 将服务器端文件以流的方式响应给客户端。
    /// </summary>
    /// <param name="aFileName">提供给客户端的默认文件名。</param>
    /// <param name="aResponseType">输出流的HTTP-MIME类型。</param>
    /// <param name="aContent">服务器上文件的全路径或内容。</param>
    /// <param name="bIsFile">服务器端信息是文件还是内容的方式。</param>
    private static void ResponseToClient(string aFileName, En_ResponseType aResponseType, string aContent, bool bIsFile) {
      HttpResponse resp = HttpContext.Current.Response;
      resp.Clear();
      resp.Buffer = true;
      switch(aResponseType) {
        case En_ResponseType.Excel:
          resp.ContentType = "application/vnd.ms-excel";
          aFileName = aFileName.ToLower().EndsWith(".xls") ? HttpUtility.UrlEncode(aFileName) : HttpUtility.UrlEncode(aFileName + ".xls");
          break;
        case En_ResponseType.Txt:
          resp.ContentType = "application/vnd.ms-txt";
          aFileName = aFileName.ToLower().EndsWith(".txt") ? HttpUtility.UrlEncode(aFileName) : HttpUtility.UrlEncode(aFileName + ".txt");
          break;
      }
      resp.AppendHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", aFileName));
      if(bIsFile) {
        resp.WriteFile(aContent);
      } else {
        resp.Write(aContent);
      }
      resp.Flush();
      resp.Close();
    }
    #endregion


如果行数不超过300行,不会报错,但是行数超过300,导出第二个就报错,或者没反应。
求大神帮忙!!!
急!!!



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2016-12-19 10:06:47 | 显示全部楼层
int maxrowcount = 300;你这是限制了吧,在第一个方法里面
 楼主| 发表于 2016-12-19 10:09:32 | 显示全部楼层
客服~小小 发表于 2016-12-19 10:06
int maxrowcount = 300;你这是限制了吧,在第一个方法里面

是呀,我是想如果超过300行,就从301行开始导出第二个excel,以后会变为60000行,现在没有那么多行,这样做测试用的。
发表于 2016-12-19 10:14:38 | 显示全部楼层
表面上也没有看出来有什么问题,
如果真是你说的这样,那么,你能跟踪到报的什么异常吗?
发表于 2016-12-19 10:17:02 | 显示全部楼层
我复制走你代码有好多错误,估计是组件不全,如果真是卡在这里,可以分批导,一批就导300个,应该也能解决你的问题
 楼主| 发表于 2016-12-19 10:17:47 | 显示全部楼层
客服~小小 发表于 2016-12-19 10:14
表面上也没有看出来有什么问题,
如果真是你说的这样,那么,你能跟踪到报的什么异常吗?

有异常,这里
resp.AppendHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", aFileName));
服务器无法在发送 HTTP 标头之后追加标头
这个语句报错。但是如果我第二次跳过这个语句的话,程序就没有任何反映了,也不下载
发表于 2016-12-20 08:14:07 | 显示全部楼层
content-disposition  错误是什么,这个如果有错,最大的可能就是文件地址不对
 楼主| 发表于 2016-12-21 13:12:14 | 显示全部楼层
站长苏飞 发表于 2016-12-20 08:14
content-disposition  错误是什么,这个如果有错,最大的可能就是文件地址不对

已解决,主要是因为一个页面多次传Response。
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-26 19:40

© 2014-2021

快速回复 返回顶部 返回列表