ASP.NET 內建 System.Drawing (GDI+) 讓伺服器端動態生成圖表成為可能。本文示範從 Access 資料庫讀取銷售資料,繪製長條圖並以圖片串流輸出。
public partial class Chart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 1. 讀取資料
DataTable dt = GetSalesData(); // 自行實作 OleDbConnection 查詢
// 2. 建立畫布
int width = 600, height = 300;
using (Bitmap bmp = new Bitmap(width, height))
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
g.SmoothingMode = SmoothingMode.AntiAlias;
// 3. 計算縮放比例
int maxValue = dt.AsEnumerable().Max(r => r.Field("SL"));
float barWidth = 30f, spacing = 10f;
float xStart = 50f, yZero = height - 40f;
float yScale = (height - 80f) / maxValue;
// 4. 繪製座標軸
g.DrawLine(Pens.Black, xStart, 40, xStart, yZero); // Y軸
g.DrawLine(Pens.Black, xStart, yZero, width - 20, yZero); // X軸
// 5. 繪製長條與標籤
for (int i = 0; i < dt.Rows.Count; i++)
{
int val = (int)dt.Rows[i]["SL"];
string month = dt.Rows[i]["YF"].ToString();
float x = xStart + spacing + i * (barWidth + spacing);
float barHeight = val * yScale;
RectangleF barRect = new RectangleF(x, yZero - barHeight, barWidth, barHeight);
// 長條漸層填充
using (LinearGradientBrush brush = new LinearGradientBrush(barRect, Color.SteelBlue, Color.LightSkyBlue, LinearGradientMode.Vertical))
g.FillRectangle(brush, barRect);
g.DrawRectangle(Pens.DarkBlue, Rectangle.Round(barRect));
// 數值標籤
g.DrawString(val.ToString(), new Font("Arial", 8), Brushes.Black, x, yZero - barHeight - 15);
// 月份標籤
g.DrawString(month, new Font("Arial", 8), Brushes.Black, x + 2, yZero + 5);
}
// 6. 輸出
Response.Clear();
Response.ContentType = "image/png";
bmp.Save(Response.OutputStream, ImageFormat.Png);
}
}
}
SmoothingMode.AntiAlias:抗鋸齒,圖表更平滑專業。LinearGradientBrush:長條漸層填充,視覺層次豐富。MeasureString:精確置中標籤,避免重疊。using 區塊:確保 Graphics、Brush、Font、Bitmap 即時釋放,防止 GDI+ 物件洩漏。<img src="Chart.aspx" alt="月度銷量長條圖" />
此模式易於擴充為餅圖、折線圖、複合圖表,並可加入快取機制 (Response.Cache) 降低重複繪圖開銷。