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

 


本文爲原創文章、源代碼爲原創代碼,如轉載/複製,請在網頁/代碼處明顯位置標明原文名稱、做者及網址,謝謝!dom


開發工具:VS2017ide

語言:C#工具

DotNet版本:.Net FrameWork 4.0及以上開發工具

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

1、GemBox.Spreadsheet工具:ui

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

下載地址:spa

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

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

2、建立Excelcode

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

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

建立Excel文件以下:

ExcelFile excel = new ExcelFile();

這裏僅僅只是建立一個excel,表明的是excel整個文件,而保存該文件的代碼以下:

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

3、給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"));

4、給excel默認字體

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

excel.DefaultFontName = "Times New Roman";

5、添加一個Sheet表格

要知道,Excel是由Sheet表格構成的,所以添加Sheet表格的代碼以下:

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

以上,已經在excel上添加了一個名爲「表格名稱」的數據表格。

6、給Sheet添加密碼保護

有時候,爲了保護本身的Excel不被篡改,須要設置一下Sheet的密碼,具體代碼以下:

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

7、讓網格線不可見

默認狀況下,Sheet的網格線是可見的,有時候,咱們能夠設置網格線不可見,具體代碼以下:

sheet.ViewOptions.ShowGridLines = false;

8、寫入單元格

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

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

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

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

以上沒有加雙引號的緣由是:內容不必定是字符串,有多是數字、日期等。

9、單元格樣式設置

單元格設置須要使用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);

10、合併單元格

合併單元格需使用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;

11、建立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";

12、給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;

十3、附上完整的源代碼

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();
        }
    }
}

十4、生成的Excel

演示的Excel下載地址:

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

十5、生成的exe

下載地址以下:

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

運行結果以下:

相關文章
相關標籤/搜索