使用 C# 在 ASPX 页面中显示 MS Excel 工作表和图表






4.66/5 (13投票s)
2006年11月9日
2分钟阅读

243648

6009
如何在 ASPX 页面中显示 Excel 表格及其格式和图表。
引言
本文的目的是展示如何在 aspx 页面中显示 Excel 表格的确切值,包括其注释。代码后文件使用 C# 编写。这里显示的方法可以显示带有格式的 Excel 表格,包括字体、颜色、对齐方式等。这对于进行 MS Office 自动化的开发人员非常有用。前提条件是在 DCOM 配置中,您的 Excel 应用程序应该被授予在服务器系统中访问和加载的权限。
Excel 格式的转换只需要几行代码。格式细节包括将 Excel 属性转换为 .NET 属性,例如将 Excel 颜色转换为 .NET Color
。
/// <SUMMARY>
/// Converts Excel Color to Dot Net Color
/// </SUMMARY>
/// Excel Object Color
/// <RETURNS>Returns System.Drawing.Color</RETURNS>
private System.Drawing.Color
ConvertExcelColor2DotNetColor(object objExcelColor)
{
string strColor = "";
uint uColor = 0;
int nRed = 0;
int nGreen = 0;
int nBlue = 0;
strColor = objExcelColor.ToString();
uColor = checked((uint)Convert.ToUInt32(strColor));
strColor = String.Format("{0:x2}", uColor);
strColor = "000000" + strColor;
strColor = strColor.Substring((strColor.Length - 6), 6);
uColor = 0;
uColor = Convert.ToUInt32(strColor.Substring(4, 2), 16);
nRed = (int)uColor;
uColor = 0;
uColor = Convert.ToUInt32(strColor.Substring(2, 2), 16);
nGreen = (int)uColor;
uColor = 0;
uColor = Convert.ToUInt32(strColor.Substring(0, 2), 16);
nBlue = (int)uColor;
return System.Drawing.Color.FromArgb(nRed, nGreen, nBlue);
}
格式细节还包括将 Excel 水平对齐方式转换为 .NET 水平对齐方式
/// <SUMMARY>
/// Converts Excel Horizontal Alignment to DotNet Horizontal Alignment
/// </SUMMARY>
/// Excel Horizontal Alignment
/// <RETURNS>HorizontalAlign</RETURNS>
private HorizontalAlign ExcelHAlign2DotNetHAlign(object objExcelAlign)
{
switch (((Excel.Range)objExcelAlign).HorizontalAlignment.ToString())
{
case "-4131":
return HorizontalAlign.Left;
case "-4108":
return HorizontalAlign.Center;
case "-4152":
return HorizontalAlign.Right;
default:
return HorizontalAlign.Left;
}
}
接下来是将 Excel 垂直对齐方式转换为 .NET 垂直对齐方式
/// <SUMMARY>
/// Converts Excel Vertical Alignment to DotNet Vertical Alignment
/// </SUMMARY>
/// Excel Vertical Alignment
/// <RETURNS>VerticalAlign</RETURNS>
private VerticalAlign ExcelVAlign2DotNetVAlign(object objExcelAlign)
{
switch (((Excel.Range)objExcelAlign).VerticalAlignment.ToString())
{
case "-4160":
return VerticalAlign.Top;
case "-4108":
return VerticalAlign.Middle;
case "-4107":
return VerticalAlign.Bottom;
default:
return VerticalAlign.Bottom;
}
}
图表视图
工作表名称的选择将以“*”分隔符显示。这是因为工作表名称中不能接受“*”。
显示工作表时遇到的问题
- 行合并未包含,因为它需要找出组合行的逻辑(而列合并可以在插入
TableRow
时实现)。 - 图表对象是一个 GIF 文件,它被生成并放置在服务器上,然后在 ASPX 页面中显示。(这里不需要将图表对象放在页面内)。这是将图表放置在 ASPX 页面上的初步尝试。
未来计划
在 ASPX 页面中显示所有类型的 MS Office 文件,并对数据值等进行智能分析。
值得考虑的要点
这满足了仅显示数据的业务需求,没有进行任何处理活动。带有对其他 Excel 文件进行单元格引用的 Excel 模板将提供实时样式表数据报告。
摘要
此页面将通过包含 MS Excel 的多个功能来增强。