.Net 通过下载链接保存Excel并打开

        public string DoExcel(string url, IDictionary<string, string> parameters, ref CookieContainer cookieContainer, ref int statusCode
, string referer = "", string accept = "", string host = "")
        {
            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/msexcel;charset=utf-8";
            if (!string.IsNullOrEmpty(referer)) req.Referer = referer;
            if (!string.IsNullOrEmpty(accept)) req.Accept = accept;
            if (!string.IsNullOrEmpty(host)) req.Host = host;
            req.CookieContainer = new CookieContainer();
            if (cookieContainer != null && cookieContainer.Count > 0)
            {
                req.CookieContainer = cookieContainer;
            }
            req.Headers.Add("X-Requested-With", "XMLHttpRequest");
            req.KeepAlive = true;
            req.Headers.Add("Accept-Language", "zh-CN");
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
            HttpWebResponse rsp = null;
            Encoding encoding = null;
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
                rsp = (HttpWebResponse)req.GetResponse();

                //垃圾回收
                System.GC.Collect();
                encoding = Encoding.GetEncoding(rsp.CharacterSet);
            }
            catch (WebException ex)
            {
                HttpWebResponse rspEx = (HttpWebResponse)ex.Response;
                if (rspEx != null) statusCode = (int)rspEx.StatusCode;
                return ex.Message;
            }
            finally
            {
                if (rsp != null) statusCode = (int)rsp.StatusCode;
            }
            return GetResponseAsExcel(rsp, encoding, thirdNumber);
        }
        public string GetResponseAsExcel(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                string baseDire = AppDomain.CurrentDomain.BaseDirectory;
                string path = System.IO.Path.Combine(baseDire, "excle\\" + DateTime.Now.ToString("yyyyMMdd") + "\\");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string returnPath = System.IO.Path.Combine(path, "_" + OptionHelper.GetUniqueIndentifier(3) + ".xls");
                if (File.Exists(returnPath))
                {
                    File.Delete(returnPath);
                }
              
                // 创建本地文件写入流
                Stream fs = new FileStream(returnPath, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = stream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    fs.Write(bArr, 0, size);
                    size = stream.Read(bArr, 0, (int)bArr.Length);
                }
                fs.Close();
                //if (rsp != null)
                //{
                //    rsp.Close();
                //}
                //return reader.ReadToEnd();
                return returnPath;
            }
            catch (Exception ex)
            {
                Logger.GetInstance().Error("解析异常:" + System.Environment.NewLine + ex.Message + ex.StackTrace);
                return null;
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
                //垃圾回收
                System.GC.Collect();
            }
        }
这样子就能通过下载链接下载excel到本地了。在怎么打开表格的时候首先想到用Epplus,因为最近就在用这个,但是很悲催,用了这个第三方组件才知道不支持xls,只支持xlsx。

除了Epplus,之前还用过NPOI,这个是支持xls的,马上用nuget下载,定义一个帮助类ExcelUtility

    public class ExcelUtility
    {
        /// <summary>  
        /// 将excel导入到datatable  
        /// </summary>  
        /// <param name="filePath">excel路径</param>  
        /// <param name="isColumnName">第一行是否是列名</param>  
        /// <returns>返回datatable</returns>  
        public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
        {
            DataTable dataTable = null;
            FileStream fs = null;
            DataColumn column = null;
            DataRow dataRow = null;
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow row = null;
            ICell cell = null;
            int startRow = 0;
            try
            {
                using (fs = File.OpenRead(filePath))
                {
                    // 2007版本  
                    if (filePath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本  
                    else if (filePath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);

                    if (workbook != null)
                    {
                        sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet  
                        dataTable = new DataTable();
                        if (sheet != null)
                        {
                            int rowCount = sheet.LastRowNum;//总行数  
                            if (rowCount > 0)
                            {
                                IRow firstRow = sheet.GetRow(0);//第一行  
                                int cellCount = firstRow.LastCellNum;//列数  

                                //构建datatable的列  
                                if (isColumnName)
                                {
                                    startRow = 1;//如果第一行是列名,则从第二行开始读取  
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        cell = firstRow.GetCell(i);
                                        if (cell != null)
                                        {
                                            if (cell.StringCellValue != null)
                                            {
                                                column = new DataColumn(cell.StringCellValue);
                                                dataTable.Columns.Add(column);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                    {
                                        column = new DataColumn("column" + (i + 1));
                                        dataTable.Columns.Add(column);
                                    }
                                }

                                //填充行  
                                for (int i = startRow; i <= rowCount; ++i)
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = "";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                            switch (cell.CellType)
                                            {
                                                case CellType.Blank:
                                                    dataRow[j] = "";
                                                    break;
                                                case CellType.Numeric:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                                    if (format == 14 || format == 31 || format == 57 || format == 58)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;
                                                case CellType.String:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                            }
                        }
                    }
                }
                return dataTable;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return null;
            }
        }
    }

调用 :using (DataTable dataTable = ExcelUtility.ExcelToDataTable(“绝对路径”, true))
完美收官。

转载于:https://www.cnblogs.com/liaojianwang/p/10818303.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Free Spire.XLS for .NET 是 Spire.XLS for .NET 的免费版本,无需购买即可用于个人或商业用途。使用 Free Spire.XLS for .NET,开发人员可以在 .NET 应用程序中快速对 Excel 文档进行各种编程操作,如根据模板创建新的 Excel 文档,编辑现有 Excel 文档以及对 Excel 文档进行转换等。Free Spire.XLS for .NET 是 Spire.XLS for .NET 的免费版本,无需购买即可用于个人或商业用途。使用 Free Spire.XLS for .NET,开发人员可以在 .NET 应用程序中快速对 Excel 文档进行各种编程操作,如根据模板创建新的 Excel 文档,编辑现有 Excel 文档以及对 Excel 文档进行转换等。 主要功能如下: 1.100% 独立的 .NET 组件,无需 Microsoft Office Automation 2.强大的,高质量的 Excel 文件转换功能。支持将 Excel 文档快速高效地转换为多种常见的格式,如 XML,Text,PDF 和图片等。 3.使用全面的工作簿设计器创建 Excel 报表。支持开发人员新建 Excel 工作簿,从文件流或文件夹加载工作簿。还可以将工作薄保存到磁盘, 文件流或 Web Response,同时提供了多种安全功能,包括 Excel 加密/解密,单元格隐藏/取消隐藏,工作表锁定/解锁。 4.自由操作工作表。允许开发人员使用 C#、VB.NET 或 ASP.NET 来创建、添加、删除、重命名、编辑和移动工作表,开发人员还可以在多个充满数据的工作表之间进行复制、调换和合并操作。这个专业的 .NET Excel 类库嵌入了很多灵活显示工作表的选项,包括分页符,缩放设置,冻结窗口,页眉/页脚,打印 Excel 文件,打印页面尺寸和打印区域等。 5.在运行时轻松操作单元格和 Excel 计算引擎。开发人员可以在运行时使用 C#、VB.NET 或 ASP.NET 轻松地操作 Excel 单元格,计算公式值。该高速、可扩展的 Excel 计算引擎与 Excel 97-2003/2007/2010 等兼容。同时该组件支持设置单元格样式,如单元格的合并/拆分,文字环绕/取消环绕,文本排列和旋转、边框、锁定/解除等。字体格式,如设置字体类型、大小、颜色、粗体、斜体、删除线、下划线等等。条件格式,文本搜索和替换,过滤和数据验证等操作都可以轻松的应用到单元格中。 6.图表、数据和其它元素。提供了一组丰富的图表,如饼状图,条形图,柱形图,折线图和雷达图等。此外,它支持使用 C#、VB.NET 或 ASP.NET 在数据库和 Excel 之间进行数据传输,支持超链接和模板,支持创建和获取数据透视表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值