Overview

  在项目中,我们经常需要将程序中获得的大量数据导出到Excel表格中,打印报表;进一步,还可能生成其折线图,对数据的变化趋势进行分析,从而更好地开展项目工作。

  最近,我发现了一个对于DotNet开发人员来说比较容易上手的Office开发组件——E-iceblue公司的Spire.XLS for .Net,我用该组件写了几个Demo,感觉还不错。在Demo中,我主要利用Spire.XLS组件将SQL Server 2008数据库中的数据导出到Excel中并将数据图表化。

  下面是E-iceblue官网对Spire.XLS for .Net组件的介绍:

  Spire.XLS for .NET is a professional Excel .NET component that can be used to any type of .NET 2.0, 3.5, 4.0 or 4.5 framework application, both ASP.NET web sites and Windows Forms application. Spire.XLS for .NET offers object model Excel API for speeding up Excel programming in .NET platform - create new Excel documents from template, edit existing Excel documents and convert Excel files.

  E-iceblue官网:http://www.e-iceblue.com/(冰蓝科技)。

Download & Installation

  首先,去官网下载Spire.XLS for .Net组件;

  双击exe程序进行安装;

Programming Guid

(1)Create a Project & Add Reference

  1)创建一个工程,我创建了一个WinForm工程;

  2)找到Spire.XLS for .Net组件的安装目录,在工程的“解决方案”窗口右击,添加引用,选择工程对应DotNet版本的组件进行添加;

(2)Using Namespace

  在本工程中,我使用的命名空间如下:

using Spire.Xls;
using Spire.Xls.Converter;
using Spire.Xls.Charts; using System.Data.SqlClient;

(3)Initialization

private DataTable dataTable = new DataTable();

private Workbook workbook = new Workbook();
private Worksheet worksheet;

(4)Database Manipulation

  在本工程中,我使用的是SQL Server 2008数据库。因为我现在没有大量的数据,为了此Demo,我先做了一些数据,不是很多,能达到效果即可。数据库中的数据如下:

  

  有了数据,我们就来连接数据库,Core Code如下:

private DataTable DBReader()
{
DataTable dataTable = new DataTable(); string strConn = "server=Gordon-PC\\SQLEXPRESS;database=DB_GHC;uid=sa;pwd=123456";
SqlConnection connSql = new SqlConnection(strConn);
connSql.Open();
if (connSql.State == ConnectionState.Open)
{
string sqlQuery = "SELECT * FROM Tb_Temperature";
SqlCommand cmdSql = new SqlCommand(sqlQuery, connSql);
SqlDataAdapter adapterSql = new SqlDataAdapter(cmdSql);
DataSet dataSet = new DataSet();
adapterSql.Fill(dataSet, "Table");
dataTable = dataSet.Tables["Table"];
}
connSql.Dispose(); //dataGridView1.DataSource = dataTable;
return dataTable;
}

  从以上代码可以看出,该方法的返回值是Datatable类型的,这是因为Spire.XLS for .Net组件需要的是Datatable类型的数据。

(5)Export Datatable to Excel

  核心代码如下所示:

private void Datatable2Excel(DataTable dataTable, Worksheet sheet)
{
sheet.InsertDataTable(dataTable, true, , ); //Style
sheet.Name = "TemperatureSheet";
sheet.GridLinesVisible = true;
sheet.Range["A1:K1"].Style.Font.IsBold = true;
sheet.Range["A2:K2"].Style.KnownColor = ExcelColors.LightYellow;
sheet.Range["A3:K3"].Style.KnownColor = ExcelColors.LightGreen1;
//Border
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeTop].Color = Color.FromArgb(, , );
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.FromArgb(, , );
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeLeft].Color = Color.FromArgb(, , );
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeRight].Color = Color.FromArgb(, , );
sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
}

(6)Create Line Chart

  核心代码如下:

private void InsertChart(Worksheet sheet)
{
//Add a new chart worsheet to workbook
Chart chart = sheet.Charts.Add(); //Set region of chart data
chart.DataRange = sheet.Range["A1:K3"];
chart.ChartType = ExcelChartType.Line; //Set position of chart
chart.LeftColumn = ;
chart.TopRow = ;
chart.RightColumn = ;
chart.BottomRow = ; chart.ChartTitle = "Tepmerature Chart";
chart.ChartTitleArea.IsBold = true;
chart.ChartTitleArea.Size = ; chart.PrimaryCategoryAxis.Title = "Day";
chart.PrimaryCategoryAxis.Font.IsBold = true;
chart.PrimaryCategoryAxis.TitleArea.IsBold = true; chart.PrimaryValueAxis.Title = "Temperature";
chart.PrimaryValueAxis.HasMajorGridLines = true;
chart.PrimaryValueAxis.TitleArea.TextRotationAngle = ;
chart.PrimaryValueAxis.MinValue = ;
chart.PrimaryValueAxis.TitleArea.IsBold = true; chart.PlotArea.Fill.Visible = false;
chart.Legend.Position = LegendPositionType.Top;
}

(7)Execute

  在Form1_Load方法中加入如下代码,让以上代码在窗体加载中得以执行。

dataTable = DBReader();

worksheet = workbook.Worksheets[];

Datatable2Excel(dataTable, worksheet);

InsertChart(worksheet);

workbook.SaveToFile("DataFromDB.xls");

System.Diagnostics.Process.Start("DataFromDB.xls");

  其中,最后一条代码是让程序打开刚才操作的Excel文件。

(8)Result

  程序执行后打开的Excel文件效果如下所示:

  

(9)Further

  在本工程中,因为不需要窗体,就将其最小化到了任务栏,核心代码如下:

/// <summary>
/// 窗体最小化到任务栏
/// </summary>
private void FormMinimizedInTaskbar()
{
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;//使Form不在任务栏上显示 this.iconNotify = new NotifyIcon();
this.iconNotify.Icon = new Icon("./Excel_2010_72px.ico");
this.iconNotify.Text = "WinFormXSL";
this.iconNotify.Visible = true;//在通知区显示Form的Icon
this.iconNotify.MouseClick+=new MouseEventHandler(iconNotify_MouseClick);
}

  单击任务栏的图标可将窗体显示出来,代码如下:

protected void iconNotify_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//左键单击
{
//this.Visible = true;
WindowState = FormWindowState.Normal;
}
else if (e.Button == MouseButtons.Right)//右键单击
{
}
}

Summary

  以上我介绍的只是Spire.XLS for .Net组件的feature之一,除此之外还有很多,如下所示:

  

Source Code

  本工程的源代码,我已将其推送到我的Github,如有需要,请访问我的GitHub网站https://github.com/GaoHongchen/WinFormSpireXLS,Fork或Download即可。