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

  自己没有找到相关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读写的详细内容.

 

posted @ 2018-02-06 10:22  Fathi  阅读(242)  评论(0编辑  收藏  举报