[C#]使用Gembox.SpreadSheet向Excel寫入數據及圖表


 


本文為原創文章、源代碼為原創代碼,如轉載/復制,請在網頁/代碼處明顯位置標明原文名稱、作者及網址,謝謝!


開發工具:VS2017

語言:C#

DotNet版本:.Net FrameWork 4.0及以上

使用的DLL工具名稱:GemBox.Spreadsheet.dll (版本:37.3.30.1185)

一、GemBox.Spreadsheet工具:

該DLL是由GemBox公司開發的基於Excel功能的開發工具,該DLL很輕量,且使用起來很方便,在這里推薦下來來使用。

下載地址:

https://pan.baidu.com/s/1slcBUqh

本文就是使用該工具進行Excel的寫入操作。

二、創建Excel

為了能使用該DLL,必須在調用前寫入以下代碼:

SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

創建Excel文件如下:

ExcelFile excel = new ExcelFile();

這里僅僅只是創建一個excel,代表的是excel整個文件,而保存該文件的代碼如下:

excel.Save("文件路徑");

三、給Excel添加一些屬性

我們可以給excel添加一些諸如文檔標題、作者、公司及備注等內容,實現這些內容的代碼如下:

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默認字體

這是給整個Excel設置統一的字體,具體代碼如下:

excel.DefaultFontName = "Times New Roman";

五、添加一個Sheet表格

要知道,Excel是由Sheet表格構成的,因此添加Sheet表格的代碼如下:

ExcelWorksheet sheet = excel.Worksheets.Add("表格名稱");

以上,已經在excel上添加了一個名為“表格名稱”的數據表格。

六、給Sheet添加密碼保護

有時候,為了保護自己的Excel不被篡改,需要設置一下Sheet的密碼,具體代碼如下:

sheet.ProtectionSettings.SetPassword("cnxy");
sheet.Protected = true;

七、讓網格線不可見

默認情況下,Sheet的網格線是可見的,有時候,我們可以設置網格線不可見,具體代碼如下:

sheet.ViewOptions.ShowGridLines = false;

八、寫入單元格

訪問單元格的方式有三種,三種分別如下:

sheet.Cells["A1"]
sheet.Cells[0,0]
sheet.Rows[0].Cells[0]

以上三種方法都可以訪問單元格,但如下寫入單元格呢,其實方法很簡單,如下:

sheet.Cells["A1"].Value= 內容

以上沒有加雙引號的原因是:內容不一定是字符串,有可能是數字、日期等。

九、單元格樣式設置

單元格設置需要使用CellStyle對象,其代碼如下:

CellStyle style = new CellStyle();
//設置水平對齊模式
style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
//設置垂直對齊模式
style.VerticalAlignment = VerticalAlignmentStyle.Center;
//設置字體
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;

設置邊框如下:

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;

十一、創建Chart圖表對象

使用的是LineChart對象,代碼如下:

LineChart chart =(LineChart)sheet.Charts.Add(ChartType.Line,"B4","J22");

以上意思是從B4到J22創建一個LineChart對象。

設置圖表標題不可見,代碼如下:

chart.Title.IsVisible = false;

設置X軸與Y軸的標題可見,代碼如下:

chart.Axes.Horizontal.Title.Text = "Time";
chart.Axes.Vertical.Title.Text = "Voltage";

十二、給Y軸設置屬性

主要使用了chart.Axes.VerticalValue返回的ValueAxis對象,代碼如下:

ValueAxis axisY =  chart.Axes.VerticalValue;
//Y軸最大刻度與最小刻度
axisY.Minimum = -100;
axisY.Maximum = 100;
//Y軸主要與次要單位大小
axisY.MajorUnit = 20;
axisY.MinorUnit = 10;
//Y軸主要與次要網格是否可見
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默認字體
            excel.DefaultFontName = TIMESNEWROMAN;
            //Excel文檔屬性設置
            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"));
            //新建一個Sheet表格
            ExcelWorksheet sheet = excel.Worksheets.Add(TITLE);
            //設置表格保護
            sheet.ProtectionSettings.SetPassword("cnxy");
            sheet.Protected = true;
            //設置網格線不可見
            sheet.ViewOptions.ShowGridLines = false;
            //定義一個B2-G3的單元格范圍
            CellRange range = sheet.Cells.GetSubrange("B2", "J3");
            range.Value = "Chart";
            range.Merged = true;
            //定義一個單元格樣式
            CellStyle style = new CellStyle();
            //設置邊框
            style.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);
            //設置水平對齊模式
            style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
            //設置垂直對齊模式
            style.VerticalAlignment = VerticalAlignmentStyle.Center;
            //設置字體
            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軸主要與次要網格是否可見
            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下載地址:

https://pan.baidu.com/s/1slDPAED

十五、生成的exe

下載地址如下:

https://pan.baidu.com/s/1nvefYvJ

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM