-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExcelDocument.cs
76 lines (67 loc) · 2.23 KB
/
ExcelDocument.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.IO;
using Core.IO.Impl;
using NPOI.XSSF.UserModel;
namespace CoreExcel
{
public class ExcelDocument: IDisposable
{
private readonly XSSFWorkbook _workbook;
private readonly bool _isShadowCopy;
private readonly string _filePath;
public IEnumerable<ExcelSheet> Sheets
{
get
{
foreach (var sheet in _workbook)
yield return new ExcelSheet(sheet);
}
}
public ExcelDocument(string filePath, bool shadowCopy = true)
{
_isShadowCopy = shadowCopy;
_filePath = InitFilePath(filePath);
var fi = new FileInfo(_filePath);
_workbook = new XSSFWorkbook(fi);
}
public ExcelDocument(Stream stream)
{
_isShadowCopy = false;
_filePath = null;
_workbook = new XSSFWorkbook(stream);
}
private string InitFilePath(string filePath)
{
if (!_isShadowCopy) return filePath;
var gen = new DefaultPathNameGenerator(postfix: ".xlsx");
var util = new DefaultTempUtil(fileNameGen: gen);
var result = util.CreateFile();
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var ws = new FileStream(result, FileMode.Create, FileAccess.Write, FileShare.None))
{
var read = 0L;
var buffer = new byte[4096];
while (read < fs.Length)
{
var currentRead = fs.Read(buffer, 0, buffer.Length);
read += currentRead;
if (currentRead != 0)
{
ws.Write(buffer, 0, currentRead);
}
}
}
}
return result;
}
public void Dispose() {
_workbook.Close();
if (_isShadowCopy)
{
File.Delete(_filePath);
}
}
}
}