SharpZipLib 提取压缩包文件并转换为NPOI中的Excel文件

本文介绍如何在ASP.NET MVC项目中使用CSharpZipLib读取用户上传的压缩包,并将其中的Excel文件解压到内存中,最终通过NPOI库将数据加载到XSSFWorkBook对象。

  自己没有找到相关API,建个随笔记录一下

  在Asp.net MVC模式下,使用CSharpZipLib读取前台上传的压缩包,然后解压,利用MemoryStream存储到内存中.再封装到Xssfworkbook对象中 .

 

 1 public ActionResult Update()
 2         {
 3             //压缩包中的文件
 4             ZipEntry zipEntry;
 5             //上传的压缩包
 6             HttpPostedFileBase uploadFile = Request.Files["txt_file"];
 7             //流的转换
 8             DateTime startTime = DateTime.Now;
 9             using (ZipInputStream zipInputStream = new ZipInputStream(uploadFile.InputStream))
10             {
11                 //遍历压缩包中的文件,历史ZipInputStream流可以读取每个文件,
12                 while ((zipEntry = zipInputStream.GetNextEntry()) != null)
13                 {
14                     Stream decompressedStream = new MemoryStream();
15                     XSSFWorkbook xSSFWorkbook = null;
16                     //缓存
17                     Byte[] buf = new byte[1024];
18                     //读取标志位
19                     int count;
20                     try
21                     {
22                         if (!zipEntry.IsFile) continue;
23                         while ((count = zipInputStream.Read(buf, 0, buf.Length)) > 0)
24                         {
25                             //写入内存
26                             decompressedStream.Write(buf, 0, count);
27                         }
28                         //指针回位
29                         decompressedStream.Position = 0;
30                         xSSFWorkbook = new XSSFWorkbook(decompressedStream);
31                         String name = zipEntry.Name;
32                         Debug.WriteLine(name);
33                         Debug.WriteLine(xSSFWorkbook.GetSheetName(2));
34                         Debug.WriteLine(xSSFWorkbook.Count);
35                     }
36                     finally
37                     {
38                         if (xSSFWorkbook != null) xSSFWorkbook.Close();
39                         if (decompressedStream != null) decompressedStream.Close();
40 
41                     }
42                 }
43             }
44 
45             DateTime endTime = DateTime.Now;
46             Debug.WriteLine(endTime - startTime);
47             return null;
48         }

 

 

学习C#不久,之后再研究下NPOI和CSharpZipLib,还有IO读写的详细内容.

 

转载于:https://www.cnblogs.com/Fathi/p/8421051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值