Office組件之Spire.XLS的DotNet操作


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, 1, 1);

    //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(0, 0, 128);
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeBottom].Color = Color.FromArgb(0, 0, 128);
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeLeft].Color = Color.FromArgb(0, 0, 128);
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
    sheet.Range["A1:K3"].Style.Borders[BordersLineType.EdgeRight].Color = Color.FromArgb(0, 0, 128);
    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 = 2;
    chart.TopRow = 5;
    chart.RightColumn = 10;
    chart.BottomRow = 30;
  
    chart.ChartTitle = "Tepmerature Chart";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;
 
    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 = 90;
    chart.PrimaryValueAxis.MinValue = 1;
    chart.PrimaryValueAxis.TitleArea.IsBold = true;

    chart.PlotArea.Fill.Visible = false;
    chart.Legend.Position = LegendPositionType.Top;
}

(7)Execute

  在Form1_Load方法中加入如下代碼,讓以上代碼在窗體加載中得以執行。

dataTable = DBReader();

worksheet = workbook.Worksheets[0];

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即可。


免責聲明!

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



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