C#使用Gembox.SpreadSheet向Excel寫入數(shù)據(jù)及圖表的實(shí)例
開發(fā)工具:VS2017
語言:C#
DotNet版本:.Net FrameWork 4.0及以上
使用的DLL工具名稱:GemBox.Spreadsheet.dll (版本:37.3.30.1185)
一、GemBox.Spreadsheet工具:
該DLL是由GemBox公司開發(fā)的基于Excel功能的開發(fā)工具,該DLL很輕量,且使用起來很方便,在這里推薦下來來使用。
下載地址:
http://xiazai.jb51.net/201712/yuanma/GemBox_Spreadsheet.zip
本文就是使用該工具進(jìn)行Excel的寫入操作。
二、創(chuàng)建Excel
為了能使用該DLL,必須在調(diào)用前寫入以下代碼:
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
創(chuàng)建Excel文件如下:
ExcelFile excel = new ExcelFile();
這里僅僅只是創(chuàng)建一個(gè)excel,代表的是excel整個(gè)文件,而保存該文件的代碼如下:
excel.Save("文件路徑");
三、給Excel添加一些屬性
我們可以給excel添加一些諸如文檔標(biāo)題、作者、公司及備注等內(nèi)容,實(shí)現(xiàn)這些內(nèi)容的代碼如下:
excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Title, TITLE)); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Author, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Company, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Comments, "By CNXY.Website: http://www.cnc6.cn"));
四、給excel默認(rèn)字體
這是給整個(gè)Excel設(shè)置統(tǒng)一的字體,具體代碼如下:
excel.DefaultFontName = "Times New Roman";
五、添加一個(gè)Sheet表格
要知道,Excel是由Sheet表格構(gòu)成的,因此添加Sheet表格的代碼如下:
ExcelWorksheet sheet = excel.Worksheets.Add("表格名稱");
以上,已經(jīng)在excel上添加了一個(gè)名為“表格名稱”的數(shù)據(jù)表格。
六、給Sheet添加密碼保護(hù)
有時(shí)候,為了保護(hù)自己的Excel不被篡改,需要設(shè)置一下Sheet的密碼,具體代碼如下:
sheet.ProtectionSettings.SetPassword("cnxy"); sheet.Protected = true;
七、讓網(wǎng)格線不可見
默認(rèn)情況下,Sheet的網(wǎng)格線是可見的,有時(shí)候,我們可以設(shè)置網(wǎng)格線不可見,具體代碼如下:
sheet.ViewOptions.ShowGridLines = false;
八、寫入單元格
訪問單元格的方式有三種,三種分別如下:
sheet.Cells["A1"] sheet.Cells[0,0] sheet.Rows[0].Cells[0]
以上三種方法都可以訪問單元格,但如下寫入單元格呢,其實(shí)方法很簡單,如下:
sheet.Cells["A1"].Value= 內(nèi)容
以上沒有加雙引號的原因是:內(nèi)容不一定是字符串,有可能是數(shù)字、日期等。
九、單元格樣式設(shè)置
單元格設(shè)置需要使用CellStyle對象,其代碼如下:
CellStyle style = new CellStyle(); //設(shè)置水平對齊模式 style.HorizontalAlignment = HorizontalAlignmentStyle.Center; //設(shè)置垂直對齊模式 style.VerticalAlignment = VerticalAlignmentStyle.Center; //設(shè)置字體 style.Font.Size = 22 * PT; //PT=20 style.Font.Weight = ExcelFont.BoldWeight; style.Font.Color = Color.Blue; sheet.Cells["A1"].Style = style;
填充方式如下:
sheet.Cells[24,1].Style.FillPattern.PatternStyle = FillPatternStyle.Solid; sheet.Rows[24].Cells[1].Style.FillPattern.PatternForegroundColor = Color.Gainsboro;
設(shè)置邊框如下:
style.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);
十、合并單元格
合并單元格需使用CellRange對象,我們可以從sheet.Cells.GetSubrange或GetSubrangeAbsolute獲得,代碼如下:
CellRange range = sheet.Cells.GetSubrange("B2", "J3"); range.Value = "Chart"; range.Merged = true; sheet.Cells.GetSubrangeAbsolute(24, 1, 24, 9).Merged = true;
十一、創(chuàng)建Chart圖表對象
使用的是LineChart對象,代碼如下:
LineChart chart =(LineChart)sheet.Charts.Add(ChartType.Line,"B4","J22");
以上意思是從B4到J22創(chuàng)建一個(gè)LineChart對象。
設(shè)置圖表標(biāo)題不可見,代碼如下:
chart.Title.IsVisible = false;
設(shè)置X軸與Y軸的標(biāo)題可見,代碼如下:
chart.Axes.Horizontal.Title.Text = "Time"; chart.Axes.Vertical.Title.Text = "Voltage";
十二、給Y軸設(shè)置屬性
主要使用了chart.Axes.VerticalValue返回的ValueAxis對象,代碼如下:
ValueAxis axisY = chart.Axes.VerticalValue; //Y軸最大刻度與最小刻度 axisY.Minimum = -100; axisY.Maximum = 100; //Y軸主要與次要單位大小 axisY.MajorUnit = 20; axisY.MinorUnit = 10; //Y軸主要與次要網(wǎng)格是否可見 axisY.MajorGridlines.IsVisible = true; axisY.MinorGridlines.IsVisible = true; //Y軸刻度線類型 axisY.MajorTickMarkType = TickMarkType.Cross; axisY.MinorTickMarkType = TickMarkType.Inside;
十三、附上完整的源代碼
using GemBox.Spreadsheet; using GemBox.Spreadsheet.Charts; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; namespace SpreadSheetChartDemo { class Program { const int PT = 20; const int LENGTH = 200; const string TIMESNEWROMAN = "Times New Roman"; const string TITLE = "Spread Sheet Chart Demo"; static void Main(string[] args) { SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY"); ExcelFile excel = new ExcelFile(); //Excel默認(rèn)字體 excel.DefaultFontName = TIMESNEWROMAN; //Excel文檔屬性設(shè)置 excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Title, TITLE)); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Author, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Company, "CNXY")); excel.DocumentProperties.BuiltIn.Add(new KeyValuePair<BuiltInDocumentProperties, string>(BuiltInDocumentProperties.Comments, "By CNXY.Website: http://www.cnc6.cn")); //新建一個(gè)Sheet表格 ExcelWorksheet sheet = excel.Worksheets.Add(TITLE); //設(shè)置表格保護(hù) sheet.ProtectionSettings.SetPassword("cnxy"); sheet.Protected = true; //設(shè)置網(wǎng)格線不可見 sheet.ViewOptions.ShowGridLines = false; //定義一個(gè)B2-G3的單元格范圍 CellRange range = sheet.Cells.GetSubrange("B2", "J3"); range.Value = "Chart"; range.Merged = true; //定義一個(gè)單元格樣式 CellStyle style = new CellStyle(); //設(shè)置邊框 style.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin); //設(shè)置水平對齊模式 style.HorizontalAlignment = HorizontalAlignmentStyle.Center; //設(shè)置垂直對齊模式 style.VerticalAlignment = VerticalAlignmentStyle.Center; //設(shè)置字體 style.Font.Size = 22 * PT; style.Font.Weight = ExcelFont.BoldWeight; style.Font.Color = Color.Blue; range.Style = style; //增加Chart LineChart chart = (LineChart)sheet.Charts.Add(ChartType.Line,"B4","J22"); chart.Title.IsVisible = false; chart.Axes.Horizontal.Title.Text = "Time"; chart.Axes.Vertical.Title.Text = "Voltage"; ValueAxis axisY = chart.Axes.VerticalValue; //Y軸最大刻度與最小刻度 axisY.Minimum = -100; axisY.Maximum = 100; //Y軸主要與次要單位大小 axisY.MajorUnit = 20; axisY.MinorUnit = 10; //Y軸主要與次要網(wǎng)格是否可見 axisY.MajorGridlines.IsVisible = true; axisY.MinorGridlines.IsVisible = true; //Y軸刻度線類型 axisY.MajorTickMarkType = TickMarkType.Cross; axisY.MinorTickMarkType = TickMarkType.Inside; Random random = new Random(); double[] data = new double[LENGTH]; for (int i=0;i< LENGTH; i++) { if( random.Next(0,100) > 50) data[i] = random.NextDouble() * 100; else data[i] = -random.NextDouble() * 100; } chart.Series.Add("Random", data); //尾部信息 range = sheet.Cells.GetSubrange("B23", "J24"); range.Value = $"Write Time:{DateTime.Now:yyyy-MM-dd HH:mm:ss} By CNXY"; range.Merged = true; //B25(三種單元格模式) sheet.Cells["B25"].Value = "http://www.cnc6.cn"; sheet.Cells[24,1].Style.FillPattern.PatternStyle = FillPatternStyle.Solid; sheet.Rows[24].Cells[1].Style.FillPattern.PatternForegroundColor = Color.Gainsboro; //B25,J25 sheet.Cells.GetSubrangeAbsolute(24, 1, 24, 9).Merged = true; string filePath = $@"{Environment.CurrentDirectory}\SheetChart.xlsx"; try { excel.Save(filePath); Process.Start(filePath); Console.WriteLine("Write successfully"); } catch(Exception ex) { Console.WriteLine(ex); } Console.Write("Press any key to continue."); Console.ReadKey(); } } }
十四、生成的Excel
演示的Excel下載地址:
http://xiazai.jb51.net/201712/yuanma/SheetChart.zip
十五、生成的exe
下載地址如下:
http://xiazai.jb51.net/201712/yuanma/SpreadSheetChartDemo.zip
運(yùn)行結(jié)果如下:
以上這篇C#使用Gembox.SpreadSheet向Excel寫入數(shù)據(jù)及圖表的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持我們。
上一篇:Audio Source組件及相關(guān)API
欄 目:C#教程
下一篇:Winform界面中實(shí)現(xiàn)菜單列表的動(dòng)態(tài)個(gè)性化配置管理方法
本文標(biāo)題:C#使用Gembox.SpreadSheet向Excel寫入數(shù)據(jù)及圖表的實(shí)例
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5369.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10C#使用Dispose模式實(shí)現(xiàn)手動(dòng)對資源的釋放
- 01-10C#3.0使用EventLog類寫Windows事件日志的方法
- 01-10C#使用windows服務(wù)開啟應(yīng)用程序的方法
- 01-10c# ArrayList的使用方法小總結(jié)
- 01-10C#使用ADO.Net部件來訪問Access數(shù)據(jù)庫的方法
- 01-10C#使用Mutex簡單實(shí)現(xiàn)程序單實(shí)例運(yùn)行的方法
- 01-10C#簡單實(shí)現(xiàn)子窗體向父窗體傳值的方法
- 01-10使用Nopcommerce為商城添加滿XX減XX優(yōu)惠券功能
- 01-10C#中yield用法使用說明


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻 器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 01-10delphi制作wav文件的方法
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10C#中split用法實(shí)例總結(jié)
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置