excel讀寫使用NPOI Library

 

參考了下列資料後

在 Server 端存取 Excel 檔案的利器:NPOI Library

改寫一下方便自己使用

參考文獻:

在 Server 端存取 Excel 檔案的利器:NPOI Library

http://msdn.microsoft.com/zh-tw/ee818993.aspx

小弟將其中的函式改寫應用,歡迎自由散布修改,有空將不定期改寫。

請於aspx.cs引用

using NPOI.HSSF.UserModel;

請於aspx.vb引用

Imports NPOI.HSSF.UserModel;

輸出格式主要有兩種:

客戶端(Client):將資料轉成位元流(Stream)後,在網頁中下載。

view source
print ?
1 // 將資料輸出成位元流
2         MemoryStream ms2 = ExcelUtility.SetFormula(ExcelUtility.RenderDataTableToExcel(table),0,"cos(5)+sin(10)",0,0) as MemoryStream;       
3        // // 設定強制下載標頭。
4         Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Download.txt"));
5         // 輸出檔案。        
6         Response.BinaryWrite(ms.ToArray());

主機端(Server);將資料轉成檔案(File)後,存在主機。

view source
print ?
1 // // 設定強制下載標頭。
2         MemoryStream ms2 = ExcelUtility.SetFormula(ExcelUtility.RenderDataTableToExcel(table),0,"cos(5)+sin(10)",0,0) as MemoryStream;             
3         //將資料輸出到主機的檔案aaa.xls
4         ExcelUtility.SetGridLine(Server.MapPath("./aaa.xls"), ms2, false, new int[] { 0 });

函式說明:

view source
print ?
01 /// 將DataTable轉成Stream輸出.
02 public static Stream RenderDataTableToExcel(DataTable SourceTable)
03 /// 將DataTable轉成Workbook(自定資料型態)輸出.
04 public static HSSFWorkbook RenderDataTableToWorkBook(DataTable SourceTable)
05 /// 將DataTable資料輸出成檔案.
06 public static void RenderDataTableToExcel(DataTable SourceTable, string FileName)
07 /// 從位元流讀取資料到DataTable.
08 public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex, bool HaveHeader)
09 /// 從位元流讀取資料到DataTable.
10 public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex, bool HaveHeader)
11 /// 將陣列輸出成位元流.
12 public static Stream RenderArrayToExcel(string ColumnName, string[,] SourceTable)
13 /// 將陣列輸出成檔案.
14 public static void RenderArrayToExcel(string FileName, string ColumnName, string[,] SourceTable)
15 /// 將陣列輸出成WorkBook(自訂資料型態).
16 public static HSSFWorkbook RenderArrayToWorkBook(string ColumnName, string[,] SourceTable)
17 /// 將位元流資料輸出成陣列.
18 public static string[,] RenderArrayFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex, bool HaveHeader)
19 /// 將位元流資料輸出成陣列.
20 public static string[,] RenderArrayFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex, bool HaveHeader)
21 /// 在位元流儲存格中建立超連結.
22 public static Stream MakeLink(Stream InputStream, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
23 /// 在檔案儲存格中建立超連結.
24 public static void MakeLink(string FileName, Stream InputStream, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
25 /// 建立新位元流並在儲存格中建立超連結.
26 public static Stream MakeLinkFromEmpty(string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
27 /// 建立新檔案並在儲存格中建立超連結.
28 public static void MakeLinkFromEmpty(string FileName, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
29 /// 設定字體顏色大小到位元流.
30 public static Stream ApplyStyleToFile(Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params string[] SheetName)
31 /// 設定字體顏色大小到位元流.
32 public static Stream ApplyStyleToFile(Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params int[] SheetIndex)
33 /// 設定字體顏色大小到檔案.
34 public static void ApplyStyleToFile(string FileName, Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params string[] SheetName)
35 /// 設定字體顏色大小到檔案.
36 public static void ApplyStyleToFile(string FileName, Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params int[] SheetIndex)
37 /// 建立空白excel檔到位元流.
38 public static Stream CreateEmptyFile(params string[] SheetName)
39 /// 建立空白excel檔到檔案.
40 public static void CreateEmptyFile(string FileName, params string[] SheetName)
41 /// 設定格線到位元流.
42 public static Stream SetGridLine(Stream InputSteam, bool haveGridLine, params string[] SheetName)
43 /// 設定格線到位元流.
44 public static Stream SetGridLine(Stream InputSteam, bool haveGridLine, params int[] SheetIndex)
45 /// 設定格線到檔案.
46 public static void SetGridLine(string FileName, Stream InputSteam, bool haveGridLine, params int[] SheetIndex)
47 /// 設定格線到檔案.
48 public static void SetGridLine(string FileName, Stream InputSteam, bool haveGridLine, params string[] SheetName)
49 /// 從位元流將資料轉成字串輸出
50 public static string ExtractStringFromFileStream(Stream InputStream)
51 /// 從檔案將資料轉成字串輸出
52 public static string ExtractStringFromFileStream(string FileName)
53 /// 設定群組到位元流.
54 public static Stream CreateGroup(string SheetName, bool IsRow, int From, int End)
55 /// 建立群組到檔案.
56 public static void CreateGroup(string FileName,string SheetName, bool IsRow, int From, int End)
57 /// 從樣板建立位元流.
58 public static Stream CreateFileStreamFromTemplate(string TemplateFileName)
59 /// 從樣板建立檔案.
60 public static void CreateFileFromTemplate(string TemplateFileName,string OutputFileName)
61 /// 嵌入圖片到位元流.
62 public static Stream EmbedImage(Stream InputStream,int SheetIndex,string PicFileName, bool IsOriginalSize , int[] RowPosition)
63 /// 嵌入圖片到檔案.
64 public static void EmbedImage(string FileName, int SheetIndex, Stream InputStream, string PicFileName, bool IsOriginalSize, int[] RowPosition)
65 /// 建立新位元流並嵌入圖片.
66 public static Stream EmbedImage(string PicFileName, bool IsOriginalSize, int[] RowPosition)
67 /// 建立新檔案並嵌入圖片.
68 public static void EmbedImage(string ExcelFileName, string PicFileName, bool IsOriginalSize, int[] RowPosition)
69 /// 合併儲存格於位元流.
70 public static Stream MergeCell(Stream InputStream, int SheetIndex, int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
71 /// 合併儲存格於檔案.
72 public static void MergeCell(string FileName, Stream InputStream, int SheetIndex, int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
73 /// 建立新位元流並合併儲存格.
74 public static Stream MergeCell(int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
75 /// 建立新檔案並合併儲存格.
76 public static void MergeCell(string FileName , int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
77 /// 設定儲存格公式於位元流.
78 public static Stream SetFormula(Stream InputStream,int SheetIndex , string Formula, int RowIndex, int ColumnIndex)
79 /// 設定儲存格公式於檔案.
80 public static void SetFormula(string FileName,Stream InputStream, int SheetIndex, string Formula, int RowIndex, int ColumnIndex)
81 /// 建立新位元流並設定儲存格公式.
82 public static Stream SetFormula(string Formula, int RowIndex, int ColumnIndex)
83 /// 建立新檔案並設定儲存格公式.
84 public static void SetFormula(string FileName, string Formula, int RowIndex, int ColumnIndex)

以下為程序碼

定義及初始化

view source
print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Data;
04 using System.IO;
05 using System.Web;
06 using NPOI;
07 using NPOI.HPSF;
08 using NPOI.HSSF;
09 using NPOI.HSSF.UserModel;
10 using NPOI.POIFS;
11 using NPOI.Util;
12 using NPOI.HSSF.Util;
13 using NPOI.HSSF.Extractor;
14 using System.Web.UI.HtmlControls;
15   
16 public static class ExcelUtility
17 {
18     public static HSSFWorkbook workbook;
19     [Flags]
20     public enum LinkType
21     {
22         網址,
23         檔案,
24         郵件,
25         內文
26     };    
27     public static void InitializeWorkbook()
28     {
29         ////create a entry of DocumentSummaryInformation
30         if (workbook == null)
31             workbook = new HSSFWorkbook();
32         //HSSFFont font1 = workbook.CreateFont();
33         //HSSFCellStyle Style = workbook.CreateCellStyle();
34         //font1.FontHeightInPoints = 10;
35         //font1.FontName = "新細明體";
36         //Style.SetFont(font1);
37         //for (int i = 0; i < workbook.NumberOfSheets; i++)
38         //{
39         //    HSSFSheet Sheets = workbook.GetSheetAt(0);
40         //    for (int k = Sheets.FirstRowNum; k <= Sheets.LastRowNum; k++)
41         //    {
42         //        HSSFRow row = Sheets.GetRow(k);
43         //        for (int l = row.FirstCellNum; l < row.LastCellNum; l++)
44         //        {
45         //            HSSFCell Cell = row.GetCell(l);
46         //            Cell.CellStyle = Style;
47         //        }
48         //    }
49         //}
50         DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
51         dsi.Company = "測試公司";
52         workbook.DocumentSummaryInformation = dsi;
53         ////create a entry of SummaryInformation
54         SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
55         si.Subject = "測試公司Excel檔案";
56         si.Title = "測試公司Excel檔案";
57         si.Author = "killysss";
58         si.Comments = "謝謝您的使用!";
59         workbook.SummaryInformation = si;
60   
61     }

Excel檔案資訊及相關應用

view source
print ?
1 #region Excel檔案資訊及相關應用
2     public static string GetCellPosition(int row, int col)
3     {
4         col = Convert.ToInt32('A') + col;
5         row = row + 1;
6         return ((char)col) + row.ToString();
7     }
8   
9     #endregion

資料形態轉換

view source
print ?
01 #region 位元流(stream)應用及與workbook轉換
02     public static void WriteSteamToFile(MemoryStream ms, string FileName)
03     {
04         FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
05         byte[] data = ms.ToArray();
06   
07         fs.Write(data, 0, data.Length);
08         fs.Flush();
09         fs.Close();
10   
11         data = null;
12         ms = null;
13         fs = null;
14     }
15     public static void WriteSteamToFile(byte[] data, string FileName)
16     {
17         FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);        
18         fs.Write(data, 0, data.Length);
19         fs.Flush();
20         fs.Close();
21         data = null;        
22         fs = null;
23     }
24     public static Stream WorkBookToStream(HSSFWorkbook InputWorkBook)
25     {
26         MemoryStream ms = new MemoryStream();
27         InputWorkBook.Write(ms);
28         ms.Flush();
29         ms.Position = 0;
30         return ms;
31     }
32     public static HSSFWorkbook StreamToWorkBook(Stream InputStream)
33     {
34         HSSFWorkbook WorkBook = new HSSFWorkbook(InputStream);
35         return WorkBook;
36     }
37     public static HSSFWorkbook MemoryStreamToWorkBook(MemoryStream InputStream)
38     {
39         HSSFWorkbook WorkBook = new HSSFWorkbook(InputStream as Stream);
40         return WorkBook;
41     }
42     public static MemoryStream WorkBookToMemoryStream(HSSFWorkbook InputStream)
43     {
44         //Write the stream data of workbook to the root directory
45         MemoryStream file = new MemoryStream();
46         InputStream.Write(file);
47         return file;
48     }
49     public static Stream FileToStream(string FileName)
50     {
51         FileInfo fi = new FileInfo(FileName);
52         if (fi.Exists == true
53         {
54             FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
55             return fs;
56         }
57         else return null;        
58     }
59     public static Stream MemoryStreamToStream(MemoryStream ms)
60     {
61         return ms as Stream;
62     }
63     #endregion

DataTable與Excel資料格式轉換

view source
print ?
001 #region DataTable與Excel資料格式轉換
002     /// <summary>
003     /// 將DataTable轉成Stream輸出.
004     /// </summary>
005     /// <param name="SourceTable">The source table.</param>
006     /// <returns></returns>
007     public static Stream RenderDataTableToExcel(DataTable SourceTable)
008     {
009         workbook = new HSSFWorkbook();
010         InitializeWorkbook();
011         MemoryStream ms = new MemoryStream();
012         HSSFSheet sheet = workbook.CreateSheet();
013         HSSFRow headerRow = sheet.CreateRow(0);
014   
015         // handling header.
016         foreach (DataColumn column in SourceTable.Columns)
017             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
018   
019         // handling value.
020         int rowIndex = 1;
021   
022         foreach (DataRow row in SourceTable.Rows)
023         {
024             HSSFRow dataRow = sheet.CreateRow(rowIndex);
025   
026             foreach (DataColumn column in SourceTable.Columns)
027             {
028                 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
029             }
030   
031             rowIndex++;
032         }
033   
034         workbook.Write(ms);
035         ms.Flush();
036         ms.Position = 0;
037   
038         sheet = null;
039         headerRow = null;
040         workbook = null;
041   
042         return ms;
043     }
044     /// <summary>
045     /// 將DataTable轉成Workbook(自定資料型態)輸出.
046     /// </summary>
047     /// <param name="SourceTable">The source table.</param>
048     /// <returns></returns>
049     public static HSSFWorkbook RenderDataTableToWorkBook(DataTable SourceTable)
050     {
051         workbook = new HSSFWorkbook();
052         InitializeWorkbook();
053         MemoryStream ms = new MemoryStream();
054         HSSFSheet sheet = workbook.CreateSheet();
055         HSSFRow headerRow = sheet.CreateRow(0);
056   
057         // handling header.
058         foreach (DataColumn column in SourceTable.Columns)
059             headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
060   
061         // handling value.
062         int rowIndex = 1;
063   
064         foreach (DataRow row in SourceTable.Rows)
065         {
066             HSSFRow dataRow = sheet.CreateRow(rowIndex);
067   
068             foreach (DataColumn column in SourceTable.Columns)
069             {
070                 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
071             }
072   
073             rowIndex++;
074         }
075         return workbook;
076     }
077   
078     /// <summary>
079     /// 將DataTable資料輸出成檔案.
080     /// </summary>
081     /// <param name="SourceTable">The source table.</param>
082     /// <param name="FileName">Name of the file.</param>
083     public static void RenderDataTableToExcel(DataTable SourceTable, string FileName)
084     {
085         MemoryStream ms = RenderDataTableToExcel(SourceTable) as MemoryStream;
086         WriteSteamToFile(ms, FileName);
087     }
088   
089     /// <summary>
090     /// 從位元流讀取資料到DataTable.
091     /// </summary>
092     /// <param name="ExcelFileStream">The excel file stream.</param>
093     /// <param name="SheetName">Name of the sheet.</param>
094     /// <param name="HeaderRowIndex">Index of the header row.</param>
095     /// <param name="HaveHeader">if set to <c>true</c> [have header].</param>
096     /// <returns></returns>
097     public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex, bool HaveHeader)
098     {
099         workbook = new HSSFWorkbook(ExcelFileStream);
100         InitializeWorkbook();
101         HSSFSheet sheet = workbook.GetSheet(SheetName);
102   
103         DataTable table = new DataTable();
104   
105         HSSFRow headerRow = sheet.GetRow(HeaderRowIndex);
106         int cellCount = headerRow.LastCellNum;
107   
108         for (int i = headerRow.FirstCellNum; i < cellCount; i++)
109         {
110             string ColumnName = (HaveHeader == true) ? headerRow.GetCell(i).StringCellValue : "f" + i.ToString();
111             DataColumn column = new DataColumn(ColumnName);
112             table.Columns.Add(column);
113         }
114   
115         int rowCount = sheet.LastRowNum;
116         int RowStart = (HaveHeader == true) ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
117         for (int i = RowStart; i <= sheet.LastRowNum; i++)
118         {
119             HSSFRow row = sheet.GetRow(i);
120             DataRow dataRow = table.NewRow();
121   
122             for (int j = row.FirstCellNum; j < cellCount; j++)
123                 dataRow[j] = row.GetCell(j).ToString();
124         }
125   
126         ExcelFileStream.Close();
127         workbook = null;
128         sheet = null;
129         return table;
130     }
131   
132     /// <summary>
133     /// 從位元流讀取資料到DataTable.
134     /// </summary>
135     /// <param name="ExcelFileStream">The excel file stream.</param>
136     /// <param name="SheetIndex">Index of the sheet.</param>
137     /// <param name="HeaderRowIndex">Index of the header row.</param>
138     /// <param name="HaveHeader">if set to <c>true</c> [have header].</param>
139     /// <returns></returns>
140     public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex, bool HaveHeader)
141     {
142         workbook = new HSSFWorkbook(ExcelFileStream);
143         InitializeWorkbook();
144         HSSFSheet sheet = workbook.GetSheetAt(SheetIndex);
145   
146         DataTable table = new DataTable();
147   
148         HSSFRow headerRow = sheet.GetRow(HeaderRowIndex);
149         int cellCount = headerRow.LastCellNum;
150   
151         for (int i = headerRow.FirstCellNum; i < cellCount; i++)
152         {
153             string ColumnName = (HaveHeader == true) ? headerRow.GetCell(i).StringCellValue : "f" + i.ToString();
154             DataColumn column = new DataColumn(ColumnName);
155             table.Columns.Add(column);
156         }
157   
158         int rowCount = sheet.LastRowNum;
159         int RowStart = (HaveHeader == true) ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
160         for (int i = RowStart; i <= sheet.LastRowNum; i++)
161         {
162             HSSFRow row = sheet.GetRow(i);
163             DataRow dataRow = table.NewRow();
164   
165             for (int j = row.FirstCellNum; j < cellCount; j++)
166             {
167                 if (row.GetCell(j) != null)
168                     dataRow[j] = row.GetCell(j).ToString();
169             }
170   
171             table.Rows.Add(dataRow);
172         }
173   
174         ExcelFileStream.Close();
175         workbook = null;
176         sheet = null;
177         return table;
178     }
179     #endregion

字串陣列與Excel資料格式轉換

view source
print ?
001 #region 字串陣列與Excel資料格式轉換
002     /// <summary>
003     /// 建立datatable
004     /// </summary>
005     /// <param name="ColumnName">欄位名用逗號分隔</param>
006     /// <param name="value">data陣列 , rowmajor</param>
007     /// <returns>DataTable</returns>
008     public static DataTable CreateDataTable(string ColumnName, string[,] value)
009     {
010         /*  輸入範例
011         string cname = " name , sex ";
012         string[,] aaz = new string[4, 2];
013         for (int q = 0; q < 4; q++)
014             for (int r = 0; r < 2; r++)
015                 aaz[q, r] = "1";
016         dataGridView1.DataSource = NewMediaTest1.Model.Utility.DataSetUtil.CreateDataTable(cname, aaz);
017         */
018         int i, j;
019         DataTable ResultTable = new DataTable();
020         string[] sep = new string[] { "," };
021   
022         string[] TempColName = ColumnName.Split(sep, StringSplitOptions.RemoveEmptyEntries);
023         DataColumn[] CName = new DataColumn[TempColName.Length];
024         for (i = 0; i < TempColName.Length; i++)
025         {
026             DataColumn c1 = new DataColumn(TempColName[i].ToString().Trim(), typeof(object));
027             ResultTable.Columns.Add(c1);
028         }
029         if (value != null)
030         {
031             for (i = 0; i < value.GetLength(0); i++)
032             {
033                 DataRow newrow = ResultTable.NewRow();
034                 for (j = 0; j < TempColName.Length; j++)
035                 {
036                     newrow[j] = string.Copy(value[i, j].ToString());
037   
038                 }
039                 ResultTable.Rows.Add(newrow);
040             }
041         }
042         return ResultTable;
043     }
044     /// <summary>
045     /// Creates the string array.
046     /// </summary>
047     /// <param name="dt">The dt.</param>
048     /// <returns></returns>
049     public static string[,] CreateStringArray(DataTable dt)
050     {
051         int ColumnNum = dt.Columns.Count;
052         int RowNum = dt.Rows.Count;
053         string[,] result = new string[RowNum, ColumnNum];
054         for (int i = 0; i < dt.Rows.Count; i++)
055         {
056             for (int j = 0; j < dt.Columns.Count; j++)
057             {
058                 result[i, j] = string.Copy(dt.Rows[i][j].ToString());
059             }
060         }
061         return result;
062     }
063     /// <summary>
064     /// 將陣列輸出成位元流.
065     /// </summary>
066     /// <param name="ColumnName">Name of the column.</param>
067     /// <param name="SourceTable">The source table.</param>
068     /// <returns></returns>
069     public static Stream RenderArrayToExcel(string ColumnName, string[,] SourceTable)
070     {
071         DataTable dt = CreateDataTable(ColumnName, SourceTable);
072         return RenderDataTableToExcel(dt);
073     }
074     /// <summary>
075     /// 將陣列輸出成檔案.
076     /// </summary>
077     /// <param name="FileName">Name of the file.</param>
078     /// <param name="ColumnName">Name of the column.</param>
079     /// <param name="SourceTable">The source table.</param>
080     public static void RenderArrayToExcel(string FileName, string ColumnName, string[,] SourceTable)
081     {
082         DataTable dt = CreateDataTable(ColumnName, SourceTable);
083         RenderDataTableToExcel(dt, FileName);
084     }
085     /// <summary>
086     /// 將陣列輸出成WorkBook(自訂資料型態).
087     /// </summary>
088     /// <param name="ColumnName">Name of the column.</param>
089     /// <param name="SourceTable">The source table.</param>
090     /// <returns></returns>
091     public static HSSFWorkbook RenderArrayToWorkBook(string ColumnName, string[,] SourceTable)
092     {
093         DataTable dt = CreateDataTable(ColumnName, SourceTable);
094         return RenderDataTableToWorkBook(dt);
095     }
096   
097     /// <summary>
098     /// 將位元流資料輸出成陣列.
099     /// </summary>
100     /// <param name="ExcelFileStream">The excel file stream.</param>
101     /// <param name="SheetName">Name of the sheet.</param>
102     /// <param name="HeaderRowIndex">Index of the header row.</param>
103     /// <param name="HaveHeader">if set to <c>true</c> [have header].</param>
104     /// <returns></returns>
105     public static string[,] RenderArrayFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex, bool HaveHeader)
106     {
107         workbook = new HSSFWorkbook(ExcelFileStream);
108         InitializeWorkbook();
109         HSSFSheet sheet = workbook.GetSheet(SheetName);
110   
111         DataTable table = new DataTable();
112   
113         HSSFRow headerRow = sheet.GetRow(HeaderRowIndex);
114         int cellCount = headerRow.LastCellNum;
115   
116         for (int i = headerRow.FirstCellNum; i < cellCount; i++)
117         {
118             DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
119             table.Columns.Add(column);
120         }
121   
122         int rowCount = sheet.LastRowNum;
123         int RowStart = (HaveHeader == true) ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
124         for (int i = RowStart; i <= sheet.LastRowNum; i++)
125         {
126             HSSFRow row = sheet.GetRow(i);
127             DataRow dataRow = table.NewRow();
128   
129             for (int j = row.FirstCellNum; j < cellCount; j++)
130                 dataRow[j] = row.GetCell(j).ToString();
131         }
132   
133         ExcelFileStream.Close();
134         workbook = null;
135         sheet = null;
136         return CreateStringArray(table);
137     }
138   
139     /// <summary>
140     /// 將位元流資料輸出成陣列.
141     /// </summary>
142     /// <param name="ExcelFileStream">The excel file stream.</param>
143     /// <param name="SheetIndex">Index of the sheet.</param>
144     /// <param name="HeaderRowIndex">Index of the header row.</param>
145     /// <param name="HaveHeader">if set to <c>true</c> [have header].</param>
146     /// <returns></returns>
147     public static string[,] RenderArrayFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex, bool HaveHeader)
148     {
149         workbook = new HSSFWorkbook(ExcelFileStream);
150         InitializeWorkbook();
151         HSSFSheet sheet = workbook.GetSheetAt(SheetIndex);
152   
153         DataTable table = new DataTable();
154   
155         HSSFRow headerRow = sheet.GetRow(HeaderRowIndex);
156         int cellCount = headerRow.LastCellNum;
157   
158         for (int i = headerRow.FirstCellNum; i < cellCount; i++)
159         {
160             DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
161             table.Columns.Add(column);
162         }
163   
164         int rowCount = sheet.LastRowNum;
165         int RowStart = (HaveHeader == true) ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
166         for (int i = RowStart; i <= sheet.LastRowNum; i++)
167         {
168             HSSFRow row = sheet.GetRow(i);
169             DataRow dataRow = table.NewRow();
170   
171             for (int j = row.FirstCellNum; j < cellCount; j++)
172             {
173                 if (row.GetCell(j) != null)
174                     dataRow[j] = row.GetCell(j).ToString();
175             }
176   
177             table.Rows.Add(dataRow);
178         }
179   
180         ExcelFileStream.Close();
181         workbook = null;
182         sheet = null;
183         return CreateStringArray(table);
184     }
185     #endregion

超連結

view source
print ?
001 #region 超連結
002     /// <summary>
003     /// 在位元流儲存格中建立超連結.
004     /// </summary>
005     /// <param name="InputStream">The input stream.</param>
006     /// <param name="SheetNameOrIndex">Index of the sheet name or.</param>
007     /// <param name="LinkName">Name of the link.</param>
008     /// <param name="LinkValueOrIndex">Index of the link value or.</param>
009     /// <param name="s1">The s1.</param>
010     /// <param name="RowIndex">Index of the row.</param>
011     /// <param name="CellIndex">Index of the cell.</param>
012     /// <returns></returns>
013     public static Stream MakeLink(Stream InputStream, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
014     {
015   
016         workbook = new HSSFWorkbook(InputStream);
017         //HSSFSheet sheet = hssfworkbook.CreateSheet("Hyperlinks");
018         ////cell style for hyperlinks
019         ////by default hyperlinks are blue and underlined        
020         InitializeWorkbook();
021         MemoryStream ms = new MemoryStream();
022         HSSFCellStyle hlink_style = workbook.CreateCellStyle();
023         HSSFFont hlink_font = workbook.CreateFont();
024         hlink_font.Underline = HSSFFont.U_SINGLE;
025         hlink_font.Color = HSSFColor.BLUE.index;
026         hlink_style.SetFont(hlink_font);
027         string ResultLinkValue = string.Empty;
028         int ResultSheet;
029         HSSFSheet sheet;
030         if (int.TryParse(SheetNameOrIndex, out ResultSheet) == true)
031             sheet = workbook.GetSheetAt(ResultSheet);
032         else
033             sheet = workbook.GetSheet(SheetNameOrIndex);
034         HSSFCell cell = sheet.CreateRow(RowIndex).CreateCell(CellIndex);
035         cell.SetCellValue(LinkName);
036         HSSFHyperlink link;
037         switch (s1.ToString())
038         {
039             case "網址": link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
040                 ResultLinkValue = string.Copy(LinkValueOrIndex);
041                 break;
042             case "檔案": link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE);
043                 ResultLinkValue = string.Copy(LinkValueOrIndex);
044                 break;
045             case "郵件": link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL);
046                 // ResultLinkValue = string.Copy(LinkValue);   
047                 ResultLinkValue = "mailto:" + LinkValueOrIndex;
048                 break;
049             case "內文":
050                 int result;
051                 link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
052                 if (int.TryParse(LinkValueOrIndex, out result) == true)
053                     ResultLinkValue = "'" + workbook.GetSheetName(result) + "'!A1";
054                 else
055                     ResultLinkValue = "'" + LinkValueOrIndex + "'!A1";
056                 break;
057             default: link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
058                 break;
059         }
060         link.Address = (ResultLinkValue);
061         cell.Hyperlink = (link);
062         cell.CellStyle = (hlink_style);
063         workbook.Write(ms);
064         ms.Flush();
065         return ms;
066     }
067     /// <summary>
068     /// 在檔案儲存格中建立超連結.
069     /// </summary>
070     /// <param name="FileName">Name of the file.</param>
071     /// <param name="InputStream">The input stream.</param>
072     /// <param name="SheetNameOrIndex">Index of the sheet name or.</param>
073     /// <param name="LinkName">Name of the link.</param>
074     /// <param name="LinkValueOrIndex">Index of the link value or.</param>
075     /// <param name="s1">The s1.</param>
076     /// <param name="RowIndex">Index of the row.</param>
077     /// <param name="CellIndex">Index of the cell.</param>
078     public static void MakeLink(string FileName, Stream InputStream, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
079     {
080         MemoryStream ms = MakeLink(InputStream, SheetNameOrIndex, LinkName, LinkValueOrIndex, s1, RowIndex, CellIndex) as MemoryStream;
081         WriteSteamToFile(ms, FileName);
082     }
083     /// <summary>
084     /// 建立新位元流並在儲存格中建立超連結.
085     /// </summary>
086     /// <param name="SheetNameOrIndex">Index of the sheet name or.</param>
087     /// <param name="LinkName">Name of the link.</param>
088     /// <param name="LinkValueOrIndex">Index of the link value or.</param>
089     /// <param name="s1">The s1.</param>
090     /// <param name="RowIndex">Index of the row.</param>
091     /// <param name="CellIndex">Index of the cell.</param>
092     /// <returns></returns>
093     public static Stream MakeLinkFromEmpty(string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
094     {
095   
096         workbook = new HSSFWorkbook();
097         HSSFSheet sheet1 = workbook.CreateSheet();
098         //HSSFSheet sheet = hssfworkbook.CreateSheet("Hyperlinks");
099         ////cell style for hyperlinks
100         ////by default hyperlinks are blue and underlined        
101         InitializeWorkbook();
102         MemoryStream ms = new MemoryStream();
103         HSSFCellStyle hlink_style = workbook.CreateCellStyle();
104         HSSFFont hlink_font = workbook.CreateFont();
105         hlink_font.Underline = HSSFFont.U_SINGLE;
106         hlink_font.Color = HSSFColor.BLUE.index;
107         hlink_style.SetFont(hlink_font);
108         string ResultLinkValue = string.Empty;
109         int ResultSheet;
110         HSSFSheet sheet;
111         if (int.TryParse(SheetNameOrIndex, out ResultSheet) == true)
112             sheet = workbook.GetSheetAt(ResultSheet);
113         else
114             sheet = workbook.GetSheet(SheetNameOrIndex);
115         HSSFCell cell = sheet.CreateRow(RowIndex).CreateCell(CellIndex);
116         cell.SetCellValue(LinkName);
117         HSSFHyperlink link;
118         switch (s1.ToString())
119         {
120             case "網址": link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
121                 ResultLinkValue = string.Copy(LinkValueOrIndex);
122                 break;
123             case "檔案": link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE);
124                 ResultLinkValue = string.Copy(LinkValueOrIndex);
125                 break;
126             case "郵件": link = new HSSFHyperlink(HSSFHyperlink.LINK_EMAIL);
127                 // ResultLinkValue = string.Copy(LinkValue);   
128                 ResultLinkValue = "mailto:" + LinkValueOrIndex;
129                 break;
130             case "內文":
131                 int result;
132                 link = new HSSFHyperlink(HSSFHyperlink.LINK_DOCUMENT);
133                 if (int.TryParse(LinkValueOrIndex, out result) == true)
134                     ResultLinkValue = "'" + workbook.GetSheetName(result) + "'!A1";
135                 else
136                     ResultLinkValue = "'" + LinkValueOrIndex + "'!A1";
137                 break;
138             default: link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
139                 break;
140         }
141         link.Address = (ResultLinkValue);
142         cell.Hyperlink = (link);
143         cell.CellStyle = (hlink_style);
144         workbook.Write(ms);
145         ms.Flush();
146         return ms;
147     }
148     /// <summary>
149     /// 建立新檔案並在儲存格中建立超連結.
150     /// </summary>
151     /// <param name="FileName">Name of the file.</param>
152     /// <param name="SheetNameOrIndex">Index of the sheet name or.</param>
153     /// <param name="LinkName">Name of the link.</param>
154     /// <param name="LinkValueOrIndex">Index of the link value or.</param>
155     /// <param name="s1">The s1.</param>
156     /// <param name="RowIndex">Index of the row.</param>
157     /// <param name="CellIndex">Index of the cell.</param>
158     public static void MakeLinkFromEmpty(string FileName, string SheetNameOrIndex, string LinkName, string LinkValueOrIndex, LinkType s1, int RowIndex, int CellIndex)
159     {
160         MemoryStream ms = MakeLinkFromEmpty(SheetNameOrIndex, LinkName, LinkValueOrIndex, s1, RowIndex, CellIndex) as MemoryStream;
161         WriteSteamToFile(ms, FileName);
162     }
163     #endregion

設定字體字形

view source
print ?
001 #region 設定字體字形
002     public static HSSFCellStyle SetCellStyle(HSSFFont InputFont)
003     {
004         InitializeWorkbook();
005         HSSFCellStyle style1 = workbook.CreateCellStyle();
006         style1.SetFont(InputFont);
007         return style1;
008     }
009     /// <summary>
010     /// 設定字體顏色大小到位元流.
011     /// </summary>
012     /// <param name="InputStream">The input stream.</param>
013     /// <param name="FontName">Name of the font.</param>
014     /// <param name="FontSize">Size of the font.</param>
015     /// <param name="IsAllSheet">if set to <c>true</c> [is all sheet].</param>
016     /// <param name="SheetName">Name of the sheet.</param>
017     /// <returns></returns>
018     public static Stream ApplyStyleToFile(Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params string[] SheetName)
019     {
020         workbook = new HSSFWorkbook(InputStream);
021         InitializeWorkbook();
022         HSSFFont font = workbook.CreateFont();
023         HSSFCellStyle Style = workbook.CreateCellStyle();
024         font.FontHeightInPoints = FontSize;
025         font.FontName = FontName;
026         Style.SetFont(font);
027         MemoryStream ms = new MemoryStream();
028         int i;
029         if (IsAllSheet == true)
030         {
031             for (i = 0; i < workbook.NumberOfSheets; i++)
032             {
033                 HSSFSheet Sheets = workbook.GetSheetAt(0);
034                 for (int k = Sheets.FirstRowNum; k <= Sheets.LastRowNum; k++)
035                 {
036                     HSSFRow row = Sheets.GetRow(k);
037                     for (int l = row.FirstCellNum; l < row.LastCellNum; l++)
038                     {
039                         HSSFCell Cell = row.GetCell(l);
040                         Cell.CellStyle = Style;
041                     }
042                 }
043             }
044         }
045         else
046         {
047             for (i = 0; i < SheetName.Length; i++)
048             {
049                 HSSFSheet Sheets = workbook.GetSheet(SheetName[i]);
050                 for (int k = Sheets.FirstRowNum; k <= Sheets.LastRowNum; k++)
051                 {
052                     HSSFRow row = Sheets.GetRow(k);
053                     for (int l = row.FirstCellNum; l < row.LastCellNum; l++)
054                     {
055                         HSSFCell Cell = row.GetCell(l);
056                         Cell.CellStyle = Style;
057                     }
058                 }
059             }
060         }
061         workbook.Write(ms);
062         ms.Flush();
063         return ms;
064     }
065     /// <summary>
066     /// 設定字體顏色大小到位元流.
067     /// </summary>
068     /// <param name="InputStream">The input stream.</param>
069     /// <param name="FontName">Name of the font.</param>
070     /// <param name="FontSize">Size of the font.</param>
071     /// <param name="IsAllSheet">if set to <c>true</c> [is all sheet].</param>
072     /// <param name="SheetIndex">Index of the sheet.</param>
073     /// <returns></returns>
074     public static Stream ApplyStyleToFile(Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params int[] SheetIndex)
075     {
076         workbook = new HSSFWorkbook(InputStream);
077         InitializeWorkbook();
078         MemoryStream ms = new MemoryStream();
079         HSSFFont font = workbook.CreateFont();
080         HSSFCellStyle Style = workbook.CreateCellStyle();
081         font.FontHeightInPoints = FontSize;
082         font.FontName = FontName;
083         Style.SetFont(font);
084         int i;
085         if (IsAllSheet == true)
086         {
087             for (i = 0; i < workbook.NumberOfSheets; i++)
088             {
089                 HSSFSheet Sheets = workbook.GetSheetAt(0);
090                 for (int k = Sheets.FirstRowNum; k <= Sheets.LastRowNum; k++)
091                 {
092                     HSSFRow row = Sheets.GetRow(k);
093                     for (int l = row.FirstCellNum; l < row.LastCellNum; l++)
094                     {
095                         HSSFCell Cell = row.GetCell(l);
096                         Cell.CellStyle = Style;
097                     }
098                 }
099             }
100         }
101         else
102         {
103             for (i = 0; i < SheetIndex.Length; i++)
104             {
105                 HSSFSheet Sheets = workbook.GetSheetAt(SheetIndex[i]);
106                 for (int k = Sheets.FirstRowNum; k <= Sheets.LastRowNum; k++)
107                 {
108                     HSSFRow row = Sheets.GetRow(k);
109                     for (int l = row.FirstCellNum; l < row.LastCellNum; l++)
110                     {
111                         HSSFCell Cell = row.GetCell(l);
112                         Cell.CellStyle = Style;
113                     }
114                 }
115             }
116         }
117         workbook.Write(ms);
118         ms.Flush();
119         return ms;
120     }
121     /// <summary>
122     /// 設定字體顏色大小到檔案.
123     /// </summary>
124     /// <param name="FileName">Name of the file.</param>
125     /// <param name="InputStream">The input stream.</param>
126     /// <param name="FontName">Name of the font.</param>
127     /// <param name="FontSize">Size of the font.</param>
128     /// <param name="IsAllSheet">if set to <c>true</c> [is all sheet].</param>
129     /// <param name="SheetName">Name of the sheet.</param>
130     public static void ApplyStyleToFile(string FileName, Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params string[] SheetName)
131     {
132         MemoryStream ms = ApplyStyleToFile(InputStream, FontName, FontSize, IsAllSheet, SheetName) as MemoryStream;
133         WriteSteamToFile(ms, FileName);
134     }
135     /// <summary>
136     /// 設定字體顏色大小到檔案.
137     /// </summary>
138     /// <param name="FileName">Name of the file.</param>
139     /// <param name="InputStream">The input stream.</param>
140     /// <param name="FontName">Name of the font.</param>
141     /// <param name="FontSize">Size of the font.</param>
142     /// <param name="IsAllSheet">if set to <c>true</c> [is all sheet].</param>
143     /// <param name="SheetIndex">Index of the sheet.</param>
144     public static void ApplyStyleToFile(string FileName, Stream InputStream, string FontName, short FontSize, bool IsAllSheet, params int[] SheetIndex)
145     {
146         MemoryStream ms = ApplyStyleToFile(InputStream, FontName, FontSize, IsAllSheet, SheetIndex) as MemoryStream;
147         WriteSteamToFile(ms, FileName);
148     }
149     #endregion

建立空白excel檔

view source
print ?
01 #region 建立空白excel檔
02     /// <summary>
03     /// 建立空白excel檔到位元流.
04     /// </summary>
05     /// <param name="SheetName">Name of the sheet.</param>
06     /// <returns></returns>
07     public static Stream CreateEmptyFile(params string[] SheetName)
08     {
09         MemoryStream ms = new MemoryStream();
10         workbook = new HSSFWorkbook();
11         InitializeWorkbook();
12         if (SheetName == null)
13         {
14             workbook.CreateSheet();
15         }
16         else
17         {
18             foreach (string temp in SheetName)
19                 workbook.CreateSheet(temp);
20         }
21         workbook.Write(ms);
22         ms.Flush();
23         return ms;
24     }
25     /// <summary>
26     /// 建立空白excel檔到檔案.
27     /// </summary>
28     /// <param name="FileName">Name of the file.</param>
29     /// <param name="SheetName">Name of the sheet.</param>
30     public static void CreateEmptyFile(string FileName, params string[] SheetName)
31     {
32         MemoryStream ms = CreateEmptyFile(SheetName) as MemoryStream;
33         WriteSteamToFile(ms, FileName);
34     }
35     #endregion

設定格線

view source
print ?
01 #region 設定格線
02     /// <summary>
03     /// 設定格線到位元流.
04     /// </summary>
05     /// <param name="InputSteam">The input steam.</param>
06     /// <param name="haveGridLine">if set to <c>true</c> [have grid line].</param>
07     /// <param name="SheetName">Name of the sheet.</param>
08     /// <returns></returns>
09     public static Stream SetGridLine(Stream InputSteam, bool haveGridLine, params string[] SheetName)
10     {
11         workbook = new HSSFWorkbook(InputSteam);
12         InitializeWorkbook();
13         MemoryStream ms = new MemoryStream();
14         if (SheetName == null)
15         {
16             for (int i = 0; i < workbook.NumberOfSheets; i++)
17             {
18                 HSSFSheet s1 = workbook.GetSheetAt(i);
19                 s1.DisplayGridlines = haveGridLine;
20             }
21         }
22         else
23         {
24             foreach (string TempSheet in SheetName)
25             {
26                 HSSFSheet s1 = workbook.GetSheet(TempSheet);
27                 s1.DisplayGridlines = haveGridLine;
28             }
29         }
30         workbook.Write(ms);
31         ms.Flush();
32         return ms; 
33     }
34     /// <summary>
35     /// 設定格線到位元流.
36     /// </summary>
37     /// <param name="InputSteam">The input steam.</param>
38     /// <param name="haveGridLine">if set to <c>true</c> [have grid line].</param>
39     /// <param name="SheetIndex">Index of the sheet.</param>
40     /// <returns></returns>
41     public static Stream SetGridLine(Stream InputSteam, bool haveGridLine, params int[] SheetIndex)
42     {
43         workbook = new HSSFWorkbook(InputSteam);
44         InitializeWorkbook();
45         MemoryStream ms = new MemoryStream();
46         if (SheetIndex == null)
47         {
48             for (int i = 0; i < workbook.NumberOfSheets; i++)
49             {
50                 HSSFSheet s1 = workbook.GetSheetAt(i);
51                 s1.DisplayGridlines = haveGridLine;
52             }
53         }
54         else
55         {
56             foreach (int TempSheet in SheetIndex)
57             {
58                 HSSFSheet s1 = workbook.GetSheetAt(TempSheet);
59                 s1.DisplayGridlines = haveGridLine;
60             }
61         }
62         workbook.Write(ms);
63         ms.Flush();
64         return ms;
65     }
66     /// <summary>
67     /// 設定格線到檔案.
68     /// </summary>
69     /// <param name="FileName">Name of the file.</param>
70     /// <param name="InputSteam">The input steam.</param>
71     /// <param name="haveGridLine">if set to <c>true</c> [have grid line].</param>
72     /// <param name="SheetIndex">Index of the sheet.</param>
73     public static void SetGridLine(string FileName, Stream InputSteam, bool haveGridLine, params int[] SheetIndex)
74     {
75         MemoryStream ms = SetGridLine(InputSteam, haveGridLine, SheetIndex) as MemoryStream;
76         WriteSteamToFile(ms, FileName);
77     }
78     /// <summary>
79     /// 設定格線到檔案.
80     /// </summary>
81     /// <param name="FileName">Name of the file.</param>
82     /// <param name="InputSteam">The input steam.</param>
83     /// <param name="haveGridLine">if set to <c>true</c> [have grid line].</param>
84     /// <param name="SheetName">Name of the sheet.</param>
85     public static void SetGridLine(string FileName, Stream InputSteam, bool haveGridLine, params string[] SheetName)
86     {
87         MemoryStream ms = SetGridLine(InputSteam, haveGridLine, SheetName) as MemoryStream;
88         WriteSteamToFile(ms, FileName);
89     }
90     #endregion

擷取字串從excel檔案

view source
print ?
01 #region 擷取字串從excel檔案
02     /// <summary>
03     /// 從位元流將資料轉成字串輸出
04     /// </summary>
05     /// <param name="InputStream">The input stream.</param>
06     /// <returns></returns>
07     public static string ExtractStringFromFileStream(Stream InputStream)
08     {
09         HSSFWorkbook HBook = new HSSFWorkbook(InputStream);
10         ExcelExtractor extractor = new ExcelExtractor(HBook);
11         return extractor.Text;
12     }
13     /// <summary>
14     /// 從檔案將資料轉成字串輸出
15     /// </summary>
16     /// <param name="FileName">Name of the file.</param>
17     /// <returns></returns>
18     public static string ExtractStringFromFileStream(string FileName)
19     {
20         FileInfo fi = new FileInfo(FileName);
21         if (fi.Exists == true)
22         {
23             using (FileStream fs = fi.Open(FileMode.Open))
24             {
25                 HSSFWorkbook HBook = new HSSFWorkbook(fs);
26                 ExcelExtractor extractor = new ExcelExtractor(HBook);
27                 return extractor.Text;
28             }
29         }
30         else return null;
31     }
32     #endregion

設定群組

view source
print ?
01 #region 設定群組
02     /// <summary>
03     /// 設定群組到位元流.
04     /// </summary>
05     /// <param name="SheetName">Name of the sheet.</param>
06     /// <param name="IsRow">if set to <c>true</c> [is row].</param>
07     /// <param name="From">From.</param>
08     /// <param name="End">The end.</param>
09     /// <returns></returns>
10     public static Stream CreateGroup(string SheetName, bool IsRow, int From, int End)
11     {
12         MemoryStream ms = new MemoryStream();
13         workbook = new HSSFWorkbook();
14         InitializeWorkbook();
15         HSSFSheet sh = workbook.CreateSheet(SheetName);
16         for (int i = 0; i <= End; i++)
17         {
18             sh.CreateRow(i);
19         }
20         if (IsRow == true)
21             sh.GroupRow(From, End);
22         else
23             sh.GroupColumn((short)From, (short)End);
24           
25         workbook.Write(ms);
26         ms.Flush();
27         return ms;
28           
29     }
30     /// <summary>
31     /// 建立群組到檔案.
32     /// </summary>
33     /// <param name="FileName">Name of the file.</param>
34     /// <param name="SheetName">Name of the sheet.</param>
35     /// <param name="IsRow">if set to <c>true</c> [is row].</param>
36     /// <param name="From">From.</param>
37     /// <param name="End">The end.</param>
38     public static void CreateGroup(string FileName,string SheetName, bool IsRow, int From, int End)
39     {
40         MemoryStream ms = CreateGroup(SheetName, IsRow, From, End) as MemoryStream;
41         WriteSteamToFile(ms, FileName);        
42     }
43     #endregion

從樣板建立檔案

view source
print ?
01 #region 從樣板建立檔案
02     /// <summary>
03     /// 從樣板建立位元流.
04     /// </summary>
05     /// <param name="TemplateFileName">Name of the template file.</param>
06     /// <returns></returns>
07     public static Stream CreateFileStreamFromTemplate(string TemplateFileName)
08     {
09         FileInfo fi = new FileInfo(TemplateFileName);
10         if (fi.Exists == true)
11         {
12             MemoryStream ms = new MemoryStream();
13             FileStream file = new FileStream(TemplateFileName, FileMode.Open, FileAccess.Read);
14             workbook = new HSSFWorkbook(file);
15             DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
16             dsi.Company = "測試公司";
17             workbook.DocumentSummaryInformation = dsi;
18             ////create a entry of SummaryInformation
19             SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
20             si.Subject = "測試公司Excel檔案";
21             si.Title = "測試公司Excel檔案";
22             si.Author = "killysss";
23             si.Comments = "謝謝您的使用!";
24             workbook.SummaryInformation = si;
25             workbook.Write(ms);
26             ms.Flush();
27             return ms;
28         }
29         else return null;
30     }
31   
32     /// <summary>
33     /// 從樣板建立檔案.
34     /// </summary>
35     /// <param name="TemplateFileName">Name of the template file.</param>
36     /// <param name="OutputFileName">Name of the output file.</param>
37     public static void CreateFileFromTemplate(string TemplateFileName,string OutputFileName)
38     {
39         FileInfo fi = new FileInfo(TemplateFileName);
40         if (fi.Exists == true)
41         {
42             MemoryStream ms = CreateFileStreamFromTemplate(TemplateFileName) as MemoryStream;
43             WriteSteamToFile(ms, OutputFileName);
44         }
45         else ;
46     }
47     #endregion

嵌入圖片

view source
print ?
001 #region 嵌入圖片
002     /// <summary>
003     /// Loads the image.
004     /// </summary>
005     /// <param name="path">The path.</param>
006     /// <param name="wb">The wb.</param>
007     /// <returns></returns>
008     public static int LoadImage(string path, HSSFWorkbook wb)
009     {
010         FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
011         byte[] buffer = new byte[file.Length];
012         file.Read(buffer, 0, (int)file.Length);
013         return wb.AddPicture(buffer, HSSFWorkbook.PICTURE_TYPE_JPEG);
014   
015     }
016     /// <summary>
017     /// 嵌入圖片到位元流.
018     /// </summary>
019     /// <param name="InputStream">The input stream.</param>
020     /// <param name="SheetIndex">Index of the sheet.</param>
021     /// <param name="PicFileName">Name of the pic file.</param>
022     /// <param name="IsOriginalSize">if set to <c>true</c> [is original size].</param>
023     /// <param name="RowPosition">The row position.</param>
024     /// <returns></returns>
025     public static Stream EmbedImage(Stream InputStream,int SheetIndex,string PicFileName, bool IsOriginalSize , int[] RowPosition)
026     {
027         workbook = new HSSFWorkbook(InputStream);
028         InitializeWorkbook();
029         MemoryStream ms = new MemoryStream();
030         HSSFSheet sheet1 = workbook.GetSheetAt(SheetIndex);
031         HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
032         //create the anchor
033         HSSFClientAnchor anchor;
034         anchor = new HSSFClientAnchor(0,0,0,0,
035             RowPosition[0], RowPosition[1], RowPosition[2], RowPosition[3]);
036         anchor.AnchorType = 2;
037         //load the picture and get the picture index in the workbook
038         HSSFPicture picture = patriarch.CreatePicture(anchor, LoadImage(PicFileName, workbook));
039         //Reset the image to the original size.
040         if(IsOriginalSize== true)
041             picture.Resize();
042         //Line Style
043         picture.LineStyle = HSSFPicture.LINESTYLE_NONE;
044         workbook.Write(ms);
045         ms.Flush();
046         return ms;
047     }
048     /// <summary>
049     /// 嵌入圖片到檔案.
050     /// </summary>
051     /// <param name="FileName">Name of the file.</param>
052     /// <param name="SheetIndex">Index of the sheet.</param>
053     /// <param name="InputStream">The input stream.</param>
054     /// <param name="PicFileName">Name of the pic file.</param>
055     /// <param name="IsOriginalSize">if set to <c>true</c> [is original size].</param>
056     /// <param name="RowPosition">The row position.</param>
057     public static void EmbedImage(string FileName, int SheetIndex, Stream InputStream, string PicFileName, bool IsOriginalSize, int[] RowPosition)
058     {
059         MemoryStream ms = EmbedImage(InputStream, SheetIndex, PicFileName, IsOriginalSize, RowPosition) as MemoryStream;
060         WriteSteamToFile(ms, FileName);
061     }
062     /// <summary>
063     /// 建立新位元流並嵌入圖片.
064     /// </summary>
065     /// <param name="PicFileName">Name of the pic file.</param>
066     /// <param name="IsOriginalSize">if set to <c>true</c> [is original size].</param>
067     /// <param name="RowPosition">The row position.</param>
068     /// <returns></returns>
069     public static Stream EmbedImage(string PicFileName, bool IsOriginalSize, int[] RowPosition)
070     {
071         workbook = new HSSFWorkbook();
072         InitializeWorkbook();
073         MemoryStream ms = new MemoryStream();
074         HSSFSheet sheet1 = workbook.CreateSheet();
075         HSSFPatriarch patriarch = sheet1.CreateDrawingPatriarch();
076         //create the anchor
077         HSSFClientAnchor anchor;
078         anchor = new HSSFClientAnchor(0, 0, 0, 0,
079             RowPosition[0], RowPosition[1], RowPosition[2], RowPosition[3]);
080         anchor.AnchorType = 2;
081         //load the picture and get the picture index in the workbook
082         HSSFPicture picture = patriarch.CreatePicture(anchor, LoadImage(PicFileName, workbook));
083         //Reset the image to the original size.
084         if (IsOriginalSize == true)
085             picture.Resize();
086         //Line Style
087         picture.LineStyle = HSSFPicture.LINESTYLE_NONE;
088         workbook.Write(ms);
089         ms.Flush();
090         return ms;
091     }
092     /// <summary>
093     /// 建立新檔案並嵌入圖片.
094     /// </summary>
095     /// <param name="ExcelFileName">Name of the excel file.</param>
096     /// <param name="PicFileName">Name of the pic file.</param>
097     /// <param name="IsOriginalSize">if set to <c>true</c> [is original size].</param>
098     /// <param name="RowPosition">The row position.</param>
099     public static void EmbedImage(string ExcelFileName, string PicFileName, bool IsOriginalSize, int[] RowPosition)
100     {
101         MemoryStream ms = EmbedImage(PicFileName, IsOriginalSize, RowPosition) as MemoryStream;
102         WriteSteamToFile(ms, ExcelFileName);
103     }
104     #endregion

合併儲存格

view source
print ?
01 #region 合併儲存格
02     /// <summary>
03     /// 合併儲存格於位元流.
04     /// </summary>
05     /// <param name="InputStream">The input stream.</param>
06     /// <param name="SheetIndex">Index of the sheet.</param>
07     /// <param name="RowFrom">The row from.</param>
08     /// <param name="ColumnFrom">The column from.</param>
09     /// <param name="RowTo">The row to.</param>
10     /// <param name="ColumnTo">The column to.</param>
11     /// <returns></returns>
12     public static Stream MergeCell(Stream InputStream, int SheetIndex, int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
13     {
14         workbook = new HSSFWorkbook(InputStream);
15         InitializeWorkbook();
16         MemoryStream ms = new MemoryStream();
17         InitializeWorkbook();        
18         HSSFSheet sheet1 = workbook.GetSheetAt(SheetIndex);
19         sheet1.AddMergedRegion(new Region(RowFrom, ColumnFrom, RowTo, ColumnTo));
20         workbook.Write(ms);
21         ms.Flush();
22         return ms;
23     }
24     /// <summary>
25     /// 合併儲存格於檔案.
26     /// </summary>
27     /// <param name="FileName">Name of the file.</param>
28     /// <param name="InputStream">The input stream.</param>
29     /// <param name="SheetIndex">Index of the sheet.</param>
30     /// <param name="RowFrom">The row from.</param>
31     /// <param name="ColumnFrom">The column from.</param>
32     /// <param name="RowTo">The row to.</param>
33     /// <param name="ColumnTo">The column to.</param>
34     public static void MergeCell(string FileName, Stream InputStream, int SheetIndex, int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
35     {
36         MemoryStream ms = MergeCell(InputStream, SheetIndex, RowFrom, ColumnFrom, RowTo, ColumnTo) as MemoryStream;
37         WriteSteamToFile(ms, FileName);
38     }
39     /// <summary>
40     /// 建立新位元流並合併儲存格.
41     /// </summary>
42     /// <param name="RowFrom">The row from.</param>
43     /// <param name="ColumnFrom">The column from.</param>
44     /// <param name="RowTo">The row to.</param>
45     /// <param name="ColumnTo">The column to.</param>
46     /// <returns></returns>
47     public static Stream MergeCell(int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
48     {
49         workbook = new HSSFWorkbook();
50         InitializeWorkbook();
51         MemoryStream ms = new MemoryStream();
52         InitializeWorkbook();
53         HSSFSheet sheet1 = workbook.CreateSheet();
54         sheet1.AddMergedRegion(new Region(RowFrom, ColumnFrom, RowTo, ColumnTo));
55         workbook.Write(ms);
56         ms.Flush();
57         return ms;
58     }
59     /// <summary>
60     /// 建立新檔案並合併儲存格.
61     /// </summary>
62     /// <param name="FileName">Name of the file.</param>
63     /// <param name="RowFrom">The row from.</param>
64     /// <param name="ColumnFrom">The column from.</param>
65     /// <param name="RowTo">The row to.</param>
66     /// <param name="ColumnTo">The column to.</param>
67     public static void MergeCell(string FileName , int RowFrom, int ColumnFrom, int RowTo, int ColumnTo)
68     {
69         MemoryStream ms = MergeCell( RowFrom, ColumnFrom, RowTo, ColumnTo) as MemoryStream;
70         WriteSteamToFile(ms, FileName);
71     }
72     #endregion

設定儲存格公式

view source
print ?
01 #region 設定儲存格公式
02     /// <summary>
03     /// 設定儲存格公式於位元流.
04     /// </summary>
05     /// <param name="InputStream">The input stream.</param>
06     /// <param name="SheetIndex">Index of the sheet.</param>
07     /// <param name="Formula">The formula.</param>
08     /// <param name="RowIndex">Index of the row.</param>
09     /// <param name="ColumnIndex">Index of the column.</param>
10     /// <returns></returns>
11     public static Stream SetFormula(Stream InputStream,int SheetIndex , string Formula, int RowIndex, int ColumnIndex)
12     {
13         //here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
14         //So we insert three sheet just like what Excel does
15         workbook = new HSSFWorkbook(InputStream);
16         InitializeWorkbook();
17         MemoryStream ms = new MemoryStream();
18         HSSFSheet sheet1 = workbook.GetSheetAt(SheetIndex);
19         sheet1.CreateRow(RowIndex).CreateCell(ColumnIndex).SetCellFormula(Formula);
20         workbook.Write(ms);
21         ms.Flush();
22         return ms;
23     }
24     /// <summary>
25     /// 設定儲存格公式於檔案.
26     /// </summary>
27     /// <param name="FileName">Name of the file.</param>
28     /// <param name="InputStream">The input stream.</param>
29     /// <param name="SheetIndex">Index of the sheet.</param>
30     /// <param name="Formula">The formula.</param>
31     /// <param name="RowIndex">Index of the row.</param>
32     /// <param name="ColumnIndex">Index of the column.</param>
33     public static void SetFormula(string FileName,Stream InputStream, int SheetIndex, string Formula, int RowIndex, int ColumnIndex)
34     {
35         MemoryStream ms = SetFormula(InputStream, SheetIndex, Formula, RowIndex, ColumnIndex) as MemoryStream;
36         WriteSteamToFile(ms, FileName);        
37     }
38     /// <summary>
39     /// 建立新位元流並設定儲存格公式.
40     /// </summary>
41     /// <param name="Formula">The formula.</param>
42     /// <param name="RowIndex">Index of the row.</param>
43     /// <param name="ColumnIndex">Index of the column.</param>
44     /// <returns></returns>
45     public static Stream SetFormula(string Formula, int RowIndex, int ColumnIndex)
46     {
47         //here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
48         //So we insert three sheet just like what Excel does
49         workbook = new HSSFWorkbook();
50         InitializeWorkbook();
51         MemoryStream ms = new MemoryStream();
52         HSSFSheet sheet1 = workbook.CreateSheet();
53         sheet1.CreateRow(RowIndex).CreateCell(ColumnIndex).SetCellFormula(Formula);
54         workbook.Write(ms);
55         ms.Flush();
56         return ms;
57     }
58     /// <summary>
59     /// 建立新檔案並設定儲存格公式.
60     /// </summary>
61     /// <param name="FileName">Name of the file.</param>
62     /// <param name="Formula">The formula.</param>
63     /// <param name="RowIndex">Index of the row.</param>
64     /// <param name="ColumnIndex">Index of the column.</param>
65     public static void SetFormula(string FileName, string Formula, int RowIndex, int ColumnIndex)
66     {
67         MemoryStream ms = SetFormula( Formula, RowIndex, ColumnIndex) as MemoryStream;
68         WriteSteamToFile(ms, FileName);
69     }
70     #endregion

你可能感兴趣的:(excel讀寫使用NPOI Library)