ホテル管理システム
ogi
yesterday 1a1c8e71fcd14858f595029f089b2d4a00202b32
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
 
namespace HotelPms.GrpcService.Util
{
    public class Excel
    {
        public static byte[] Export(DataTable dt, string type = "xlsx")
        {            
            const int headerRowIndex = 0;
 
            // ブック作成
            IWorkbook book;
            switch (type)
            {
                case "xls":
                    book = new HSSFWorkbook();
                    break;
                case "xlsx":
                    book = new XSSFWorkbook();
                    break;
                default:
                    return null;
            }
 
            // シート作成
            var sheet = book.CreateSheet("Table");
 
            // ヘッダ行作成
            var headerRow = sheet.CreateRow(0);
            foreach (DataColumn col in dt.Columns)
            {
                ICell cell = headerRow.CreateCell(dt.Columns.IndexOf(col));
                cell.SetCellValue(col.ColumnName);
            }
 
            // データ行作成
            foreach (DataRow row in dt.Rows)
            {
                var dataRow = sheet.CreateRow(headerRowIndex + 1 + dt.Rows.IndexOf(row));
 
                foreach (DataColumn col in dt.Columns)
                {
                    var colIndex = dt.Columns.IndexOf(col);
                    if (row[colIndex] == DBNull.Value) continue;
 
                    ICell cell = dataRow.CreateCell(colIndex);
                    cell.SetCellValue(row[colIndex].ToString());
                }
            }
 
            // ブックを出力(保存)
            using (var ms = new MemoryStream())
            {
                book.Write(ms, true);
                byte[] data = ms.ToArray();
                ms.Close();
                return data;
            }
        }
    }
}