C# 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=20style.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 = [email protected]"{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

运行结果如下:

时间: 2024-08-29 05:57:22

C# Excel写入数据及图表的相关文章

excel 写入数据并发送到指定邮箱

今天公司要实现这个功能就搜索并实现了 附上代码,方便以后使用: excel操作类 static String Filename = "C:/Users/Administrator/Desktop/new.xlsx"; /** * 生成一个Excel文件 */ public static void writeExcel(String name) { WritableWorkbook wwb = null; try { // 创建一个可写入的工作薄(Workbook)对象 wwb = Wo

python3.4对已经存在的excel写入数据

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # __author__ = "blzhu" 4 """ 5 python study 6 Date:2017 7 """ 8 from xlrd import open_workbook 9 import os 10 from os.path import join 11 from xlutils.copy import c

往Excel中快速写入数据的又一种方法

往Excel写入数据的方法比较多,但实际应用场景及对性能的要求决定了需要对方法有所取舍.一些具体情形和方法可以参见https://blog.csdn.net/u013109267/article/details/52651647?locationNum=2&fps=1 但受到.Net framework及Excel版本的影响,一些比较旧的方法不再有效.比如上面网页中快速写入的关键方法get_Range和set_Value在新的VSTO环境中就受到影响.但原帖中的思路跟方法是可以借鉴的: //将T

java poi 从服务器下载模板写入数据再导出

最近写了一个,Excel 的 写入和导出.   需求是这样的.   在新建合同的时候,会有导出合同的数据,    导出的模板是固定的,,需要在模板里面写入合同的信息. first   :  下载模板   > 写入数据 > 输出 下载模板  : StringBuilder path = new StringBuilder(""); path.append(request.getSession().getServletContext().getRealPath("&q

tablib把数据导出为Excel、JSON、CSV等格式的Py库(写入数据并导出exl)

#tablib把数据导出为Excel.JSON.CSV等格式的Py库 #python 3 import tablib #定义列标题 headers = ('1列', '2列', '3列', '4列', '5列') #需写入的数据,按照一行一行的输入 #元组数据的个数必须和列数一致 data = [('23','23','34','23','34'),('sadf','23','sdf','23','fsad')] #写入数据 mylist = tablib.Dataset(*data, head

NPOI 创建Excel,数据读取与写入

<1> using System; using System.Collections.Generic; using System.Linq; using System.Web; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Formula.Functions; using System.IO; using System.Text; namespace 导入导出Excel { /// <summary&g

EXCEL页面数据快速写入SQL数据库

将EXCEL数据存入SQL表, 一万行记录大概5秒 Dim conn As New ADODB.Connection Dim CNN As New ADODB.Connection 'Dim rst As New ADODB.Recordset Dim Sql As String Dim j, v As Integer Const cnnstr = "Provider = SQLOLEDB;" & _ "Data Source = ip;" & _

java向Excel文件写入数据

/*使用之前要记得导入第三的jar包这个是我之前使用的时候那别人的东西自己修改了一下 还没来得及好好地封装一下还望见谅,注释我感觉写的挺清楚的就在不进行解释代码了*/ package com.zzp.ExcelParse; import jxl.Workbook;import jxl.format.*;import jxl.format.Alignment;import jxl.format.Border;import jxl.format.BorderLineStyle;import jxl.

Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据

背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlwt 其实是没有直接实现: 打开已有的excel文件,然后在文件最后写入,添加新数据 的函数的. 只不过,可以利用: Working with Excel Files in Python 中的库,组合实现. 2. writing to existing workbook using xlwt 给出了示