本文原創,轉載請註明出處:http://www.cnblogs.com/AdvancePikachu/p/6893934.html 本文學習如何把數據轉存為Excel文件並調用SaveFileDialog視窗進行保存。 首先需要引用幾個Plugins :System.Windows.Forms(Sa ...
本文原創,轉載請註明出處:http://www.cnblogs.com/AdvancePikachu/p/6893934.html
本文學習如何把數據轉存為Excel文件並調用SaveFileDialog視窗進行保存。
首先需要引用幾個Plugins :System.Windows.Forms(SaveFileDialog視窗) NOPI(Excel文件的數據儲存)。
調用SaveFileDialog視窗的代碼:
1 public static void OpenDialog(Action<Stream> onSave){ 2 using (SaveFileDialog saveFile = new SaveFileDialog()){ 3 saveFile.Title = "保存文件"; 4 saveFile.Filter = "Excel files(*.xls)|*.xls|All files(*.*)|*.*"; 5 saveFile.InitialDirectory = UnityEngine.Application.dataPath; 6 if(saveFile.ShowDialog()==DialogResult.OK){ 7 using(Stream s=saveFile.OpenFile()){ 8 if (onSave != null) 9 onSave (s); 10 } 11 12 string Savepath = Path.GetDirectoryName (saveFile.FileName); 13 14 Process.Start (Savepath); 15 } 16 } 17 }
需要保存其他類型的文件可以把上述代碼修改為自己想要的即可。
效果圖如下:
可惜視窗是英文的,查閱了很多資料,發現漢化會有問題,故如果有小伙伴知道如何漢化,一定要記得聯繫——AdvancePikachu。
接下來是Excel文件的數據儲存,代碼如下:
1 public void WriteToStream(Stream s) 2 { 3 IWorkbook workbook = new HSSFWorkbook (); 4 ISheet sheet = workbook.CreateSheet (); 5 6 IRow row = sheet.CreateRow (0);//參數0表示第0行 7 8 string[] firstRow = new string[] 9 { 10 "ID", 11 "性別", 12 "博客" 13 }; 14 15 for (int i = 0; i < firstRow.Length; i++) 16 { 17 ICell cell = row.CreateCell (i); 18 cell.SetCellValue (firstRow [i]); 19 } 20 21 IRow row2 = sheet.CreateRow (1); 22 23 string[] secondRow = new string[] 24 { 25 "AdvancePikachu", 26 "男", 27 "http://www.cnblogs.com/AdvancePikachu/" 28 }; 29 30 for (int i = 0; i < secondRow.Length; i++) 31 { 32 ICell cell = row2.CreateCell (i); 33 cell.SetCellValue (secondRow [i]); 34 } 35 36 workbook.Write (s); 37 }
保存的數據和行列可以自行設置,效果圖如下:
當然,最後把調用第一個腳本的方法也分享下,
代碼如下:
1 void save() 2 { 3 SaveDialog.OpenDialog (saveExcel); 4 } 5 6 void saveExcel(Stream s) 7 { 8 ExcelWrite ew = new ExcelWrite (); 9 ew.WriteToStream (s); 10 }
好了,調用SaveFileDialog保存Excel文件的學習就告一段落了。