Microsoft® Excel 檔案圖表建立與轉換 via .NET
在基於 .NET 的應用程式中使用伺服器端 API 建立 Excel 文件圖表並轉換為影像。
繪製圖表是一門以圖形方式顯示數據以便於分析的藝術。 .NET Excel 庫 支援在Excel檔案中繪製圖表。 API 支援中列出的不同圖表創建 圖表類型枚舉 包括圓餅圖、金字塔圖、折線圖和氣泡圖。此外,它還將圖表轉換為圖像。 API 提供 圖表類 用於圖表構建塊。
在 Excel 檔案中建立圖表
使用 Excel API 建立圖表很簡單。流程是,創建 作業本類 物件並透過提供其索引來選擇第一個工作表或相關工作表。使用插入所需的儲存格數據 價值法 。使用 Charts 集合將圖表新增至工作表 添加方法 。指定 圖表類型 來自 ChartType 枚舉。
C# 建立 Excel 圖表的程式碼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instantiating a Workbook object | |
Workbook wkb = new Workbook(); | |
// Obtaining the reference of the first worksheet | |
Worksheet wks = workbook.Worksheets[0]; | |
// Adding sample values to cells | |
wks.Cells["A2"].PutValue("Category1"); | |
wks.Cells["A3"].PutValue("Category2"); | |
wks.Cells["A4"].PutValue("Category3"); | |
wks.Cells["B1"].PutValue("Column1"); | |
wks.Cells["B2"].PutValue(4); | |
wks.Cells["B3"].PutValue(20); | |
wks.Cells["B4"].PutValue(50); | |
wks.Cells["C1"].PutValue("Column2"); | |
wks.Cells["C2"].PutValue(50); | |
wks.Cells["C3"].PutValue(100); | |
wks.Cells["C4"].PutValue(150); | |
// Adding a chart to the worksheet | |
int chartIndex = wks.Charts.Add(Aspose.Cells.Charts.ChartType.Column, 5, 0, 15, 5); | |
// Accessing the instance of the newly added chart | |
Aspose.Cells.Charts.Chart chart = wks.Charts[chartIndex]; | |
// Setting chart data source as the range "A1:C4" | |
chart.SetChartDataRange("A1:C4", true); | |
// Saving the Excel file | |
wkb.Save(dataDir + "output.xls"); | |
// API supports creating Pyramid, Line and Bubble chart as well |
將 Excel 圖表轉換為影像
將圖表轉換為圖像的過程是,使用 Workbook 類別載入 Excel 文件,選擇包含圖表的相關工作集並調用 影像方法 用於轉換。
C# 將Excel圖表轉換為圖像的程式碼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load Excel XLSX document having pie chart | |
var workbook = new Workbook("PieChart.xlsx"); | |
// get the designer chart (first chart) in the first worksheet of the workbook | |
var chart = workbook.Worksheets[0].Charts[0]; | |
// convert the chart to an image file. | |
chart.ToImage("PieChartOut.emf", System.Drawing.Imaging.ImageFormat.Emf); |