OWC做电子表格和图表的试验
连续这么多天持续写SQL,晚上找资料研究一下Microsoft Office Web Components(续上一篇Excel的文章)调节一下自己,和上一篇文章的主题一样,这篇主要研究OWC做报表的方法。先看一下示例的效果:
A、B效果如图:
运行效果如下:
3、图表ChartSpace类的例子,网上比较多,直接看综合示例,就不另作说明了。
一、主要内容:
1、 OWC组件在web页面展示的几种方法。
2、 OWC数据的填充。
3、 OWC显示格式的设置。
4、 在OWC中的电子表格类中填充数据的方法。
5、 OWC中显示数据格式的控制。
二、要点总结:
1、 OWC组件在web页面展示的方法。
A、将数据导出成Excel临时文件,再将临时文件呈现到Web页面,代码如下:
Sheet.Export(FileName, OWC11.SheetExportActionEnum.ssExportActionNone, OWC11.SheetExportFormat.ssExportHTML);//Sheet为OWC11中SpreadsheetClass类的对象
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename='我的文件'");
Response.WriteFile(FileName);
Response.Flush();
Response.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename='我的文件'");
Response.WriteFile(FileName);
Response.Flush();
Response.Close();
B、 不导出到本地临时文件,直接从内存加载到Web页面,代码如下:
Response.Clear();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.Default;
//Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(Sheet.HTMLData);
this.EnableViewState = false;
Response.End();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.Default;
//Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(Sheet.HTMLData);
this.EnableViewState = false;
Response.End();
A、B效果如图:
C、标签:
<object id="Spreadsheet1" classid="clsid:0002E559-0000-0000-C000-000000000046" name="Spreadsheet1">
效果如图:
2、在OWC中的电子表格类中填充数据的方法:
2、在OWC中的电子表格类中填充数据的方法:
OWC11.SpreadsheetClass Sheet = new OWC11.SpreadsheetClass();
//第一行为报表的标题
Sheet.ActiveCell[1, 1] = "报表的标题";
//逐行写入数据,数组中第一行为报表的列标题
for (int i = 0; i < DT.Columns.Count - 3; i++)
{
Sheet.Cells[2, 1 + i] = DT.Columns[i].Caption; ;
}
//为报表填充数据并设置显示上下标格式
for (int i = 0; i < DT.Rows.Count; i++)
{
for (int j = 0; j < DT.Columns.Count - 4; j++)
{
Sheet.ActiveCell[3 + i, 1 + j] = DT.Rows[i][j];
}
string a = DT.Rows[i][DT.Columns.Count - 4].ToString();
string b = DT.Rows[i][DT.Columns.Count - 3].ToString();
string c = DT.Rows[i][DT.Columns.Count - 2].ToString();
Sheet.ActiveCell[3 + i,DT.Columns.Count - 3] = a + b + c;
Sheet.Columns.AutoFit();
}
3、 OWC中数据显示格式的控制(没找到控制上下标格式数据的方法):
以下是对输出Excel的格式控制
//第一行为报表的标题
Sheet.ActiveCell[1, 1] = "报表的标题";
//逐行写入数据,数组中第一行为报表的列标题
for (int i = 0; i < DT.Columns.Count - 3; i++)
{
Sheet.Cells[2, 1 + i] = DT.Columns[i].Caption; ;
}
//为报表填充数据并设置显示上下标格式
for (int i = 0; i < DT.Rows.Count; i++)
{
for (int j = 0; j < DT.Columns.Count - 4; j++)
{
Sheet.ActiveCell[3 + i, 1 + j] = DT.Rows[i][j];
}
string a = DT.Rows[i][DT.Columns.Count - 4].ToString();
string b = DT.Rows[i][DT.Columns.Count - 3].ToString();
string c = DT.Rows[i][DT.Columns.Count - 2].ToString();
Sheet.ActiveCell[3 + i,DT.Columns.Count - 3] = a + b + c;
Sheet.Columns.AutoFit();
}
3、 OWC中数据显示格式的控制(没找到控制上下标格式数据的方法):
以下是对输出Excel的格式控制
运行效果如下:
3、图表ChartSpace类的例子,网上比较多,直接看综合示例,就不另作说明了。
三、综合示例:
注释很全,就不加说明了。
CS文件:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Data.OleDb;
using System.IO;
using System.Diagnostics;
//using OWC11 = Microsoft.Office.Interop.Owc11;
public partial class Output : System.Web.UI.Page
{
//取数据的全局变量
OleDbConnection Olecn;
OleDbCommand OleCamm;
DataTable DT = new DataTable();
//实例化OWC11
OWC11.SpreadsheetClass Sheet = new OWC11.SpreadsheetClass();
//跨框架传参用
private String StrTime = "";
//导出电子表格的全路径
public String FileName;
//导出图片的全路径
public String PicPath;
protected void Page_Load(object sender, EventArgs e)
{
//接收Input框架传递的参数
if (!IsPostBack)
{
StrTime = Request.QueryString["Time"];
if (StrTime != null)
Label1.Text = "时间:" + StrTime;
}
//在页面加载的时候将数据取出
if (ConnectionDataBase())
{
OleCamm = new OleDbCommand();
OleCamm.Connection = Olecn;
Olecn.Open();
OleCamm.CommandText = "select * from pl where date = " + "'" + StrTime + "'";
OleDbDataAdapter OleDAdp = new OleDbDataAdapter(OleCamm);
OleDAdp.Fill(DT);
Olecn.Close();
}
Exceltest();
ChartsTest();
}
/// <summary>
/// 连接数据库
/// </summary>
/// <returns></returns>
private bool ConnectionDataBase()
{
try
{
string DataSource = Server.MapPath("~") + "\\App_Data\\Excel.mdb";
Olecn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+DataSource);
Olecn.Open();
}
catch (Exception e1)
{
Response.Write(e1.Message);
return false;
}
finally
{
Olecn.Close();
}
return true;
}
/// <summary>
/// OWC中SpreadsheetClass类的操作
/// </summary>
private void Exceltest()
{
//将已经打开的Excel资源释放掉
EndExcelProcesse();
//第一行为报表的标题
Sheet.ActiveCell[1, 1] = "报表的标题栏";
//逐行写入数据,报表的列标题
for (int i = 0; i < DT.Columns.Count - 3; i++)
{
Sheet.Cells[2, 1 + i] = DT.Columns[i].Caption; ;
}
//为报表填充数据
for (int i = 0; i < DT.Rows.Count; i++)
{
for (int j = 0; j < DT.Columns.Count - 4; j++)
{
Sheet.ActiveCell[3 + i, 1 + j] = DT.Rows[i][j];
}
//下边准备显示上下标格式的,至今没有找到方法
string a = DT.Rows[i][DT.Columns.Count - 4].ToString();
string b = DT.Rows[i][DT.Columns.Count - 3].ToString();
string c = DT.Rows[i][DT.Columns.Count - 2].ToString();
Sheet.ActiveCell[3 + i,DT.Columns.Count - 3] = a + b + c;
Sheet.Columns.AutoFit();
}
以下是对输出Excel的格式控制
FileName = Server.MapPath("~") + "\\Temp.html";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
//将Sheet导出成html格式的数据,在前台页面显示用
Sheet.Export(FileName, OWC11.SheetExportActionEnum.ssExportActionNone, OWC11.SheetExportFormat.ssExportHTML);
/*
* 可以直接用下面两种方法在页面上显示,用下面的方式显示时,导出的文件格式为:.xls
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename='我的文件'");
Response.WriteFile(FileName);
Response.Flush();
Response.Close();
Response.Clear();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.Default;
//Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(Sheet.HTMLData);
this.EnableViewState = false;
Response.End();
*/
}
/// <summary>
/// 绘制图表
/// </summary>
private void ChartsTest()
{
//创建ChartSpace对象来放置图表
OWC11.ChartSpace objCSpace = new OWC11.ChartSpaceClass();
//在ChartSpace对象中添加图表,Add方法返回chart对象
OWC11.ChChart objChart = objCSpace.Charts.Add(0);
//指定图表的类型。类型由OWC11.ChartChartTypeEnum枚举值得到
objChart.Type = OWC11.ChartChartTypeEnum.chChartTypeColumnClustered;
//指定图表是否需要图例
objChart.HasLegend = true;
//给定标题
objChart.HasTitle = true;
objChart.Title.Caption = "柱状图";
//给定x,y轴的图示说明
objChart.Axes[0].HasTitle = true;
objChart.Axes[0].Title.Caption = "X: 数量";
objChart.Axes[1].HasTitle = true;
objChart.Axes[1].Title.Caption = "Y: 月份";
//计算数据
/*categories 和 values 可以用tab分割的字符串来表示*/
string strSeriesName = "图例 1";
string strCategory = "1" + '\t' + "2" + '\t' + "3" + '\t' + "4" + '\t' + "5" + '\t' + "6" + '\t';
string strValue = "9" + '\t' + "8" + '\t' + "4" + '\t' + "10" + '\t' + "12" + '\t' + "6" + '\t';
//添加一个series
objChart.SeriesCollection.Add(0);
//图例
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimSeriesNames, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strSeriesName);
//X轴
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimCategories, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strCategory);
//柱面
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimValues, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strValue);
//输出成图片文件.
PicPath = Server.MapPath("~") + "\\test.htm";
objCSpace.ExportPicture(PicPath, "jpg", 600, 350);
//FileStream fs = new FileStream(PicPath, FileMode.Open, FileAccess.Read);
//byte[] bytes = new byte[fs.Length];
//fs.Read(bytes, 0, bytes.Length);
//fs.Close();
//MemoryStream ms = new MemoryStream(bytes);
//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
//Response.ContentType = "image/jpg";
//Response.Write(img);
//Response.Write("<img src="+PicPath +"/>");
}
/// <summary>
/// 当报表数据更新时,先强制结束前一个报表的数据源
/// 这种方法会同时杀死掉用户的excel进程
/// </summary>
protected void EndExcelProcesse()
{
try
{
Process[] myProcesses = Process.GetProcessesByName("excel");
foreach (Process instance in myProcesses)
{
instance.Kill(); //强制终止
}
}
catch { }
}
/*
* 用Response.Write在页面显示时,页面卸载时删除.xls文件
protected void Page_UnLoad(object sender, EventArgs e)
{
EndExcelProcesse();
string FileName = Server.MapPath("~") + "\\Temp.xls";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
}
*/
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Data.OleDb;
using System.IO;
using System.Diagnostics;
//using OWC11 = Microsoft.Office.Interop.Owc11;
public partial class Output : System.Web.UI.Page
{
//取数据的全局变量
OleDbConnection Olecn;
OleDbCommand OleCamm;
DataTable DT = new DataTable();
//实例化OWC11
OWC11.SpreadsheetClass Sheet = new OWC11.SpreadsheetClass();
//跨框架传参用
private String StrTime = "";
//导出电子表格的全路径
public String FileName;
//导出图片的全路径
public String PicPath;
protected void Page_Load(object sender, EventArgs e)
{
//接收Input框架传递的参数
if (!IsPostBack)
{
StrTime = Request.QueryString["Time"];
if (StrTime != null)
Label1.Text = "时间:" + StrTime;
}
//在页面加载的时候将数据取出
if (ConnectionDataBase())
{
OleCamm = new OleDbCommand();
OleCamm.Connection = Olecn;
Olecn.Open();
OleCamm.CommandText = "select * from pl where date = " + "'" + StrTime + "'";
OleDbDataAdapter OleDAdp = new OleDbDataAdapter(OleCamm);
OleDAdp.Fill(DT);
Olecn.Close();
}
Exceltest();
ChartsTest();
}
/// <summary>
/// 连接数据库
/// </summary>
/// <returns></returns>
private bool ConnectionDataBase()
{
try
{
string DataSource = Server.MapPath("~") + "\\App_Data\\Excel.mdb";
Olecn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+DataSource);
Olecn.Open();
}
catch (Exception e1)
{
Response.Write(e1.Message);
return false;
}
finally
{
Olecn.Close();
}
return true;
}
/// <summary>
/// OWC中SpreadsheetClass类的操作
/// </summary>
private void Exceltest()
{
//将已经打开的Excel资源释放掉
EndExcelProcesse();
//第一行为报表的标题
Sheet.ActiveCell[1, 1] = "报表的标题栏";
//逐行写入数据,报表的列标题
for (int i = 0; i < DT.Columns.Count - 3; i++)
{
Sheet.Cells[2, 1 + i] = DT.Columns[i].Caption; ;
}
//为报表填充数据
for (int i = 0; i < DT.Rows.Count; i++)
{
for (int j = 0; j < DT.Columns.Count - 4; j++)
{
Sheet.ActiveCell[3 + i, 1 + j] = DT.Rows[i][j];
}
//下边准备显示上下标格式的,至今没有找到方法
string a = DT.Rows[i][DT.Columns.Count - 4].ToString();
string b = DT.Rows[i][DT.Columns.Count - 3].ToString();
string c = DT.Rows[i][DT.Columns.Count - 2].ToString();
Sheet.ActiveCell[3 + i,DT.Columns.Count - 3] = a + b + c;
Sheet.Columns.AutoFit();
}
以下是对输出Excel的格式控制
FileName = Server.MapPath("~") + "\\Temp.html";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
//将Sheet导出成html格式的数据,在前台页面显示用
Sheet.Export(FileName, OWC11.SheetExportActionEnum.ssExportActionNone, OWC11.SheetExportFormat.ssExportHTML);
/*
* 可以直接用下面两种方法在页面上显示,用下面的方式显示时,导出的文件格式为:.xls
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename='我的文件'");
Response.WriteFile(FileName);
Response.Flush();
Response.Close();
Response.Clear();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.Default;
//Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
Response.Write(Sheet.HTMLData);
this.EnableViewState = false;
Response.End();
*/
}
/// <summary>
/// 绘制图表
/// </summary>
private void ChartsTest()
{
//创建ChartSpace对象来放置图表
OWC11.ChartSpace objCSpace = new OWC11.ChartSpaceClass();
//在ChartSpace对象中添加图表,Add方法返回chart对象
OWC11.ChChart objChart = objCSpace.Charts.Add(0);
//指定图表的类型。类型由OWC11.ChartChartTypeEnum枚举值得到
objChart.Type = OWC11.ChartChartTypeEnum.chChartTypeColumnClustered;
//指定图表是否需要图例
objChart.HasLegend = true;
//给定标题
objChart.HasTitle = true;
objChart.Title.Caption = "柱状图";
//给定x,y轴的图示说明
objChart.Axes[0].HasTitle = true;
objChart.Axes[0].Title.Caption = "X: 数量";
objChart.Axes[1].HasTitle = true;
objChart.Axes[1].Title.Caption = "Y: 月份";
//计算数据
/*categories 和 values 可以用tab分割的字符串来表示*/
string strSeriesName = "图例 1";
string strCategory = "1" + '\t' + "2" + '\t' + "3" + '\t' + "4" + '\t' + "5" + '\t' + "6" + '\t';
string strValue = "9" + '\t' + "8" + '\t' + "4" + '\t' + "10" + '\t' + "12" + '\t' + "6" + '\t';
//添加一个series
objChart.SeriesCollection.Add(0);
//图例
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimSeriesNames, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strSeriesName);
//X轴
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimCategories, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strCategory);
//柱面
objChart.SeriesCollection[0].SetData(OWC11.ChartDimensionsEnum.chDimValues, (int)OWC11.ChartSpecialDataSourcesEnum.chDataLiteral, strValue);
//输出成图片文件.
PicPath = Server.MapPath("~") + "\\test.htm";
objCSpace.ExportPicture(PicPath, "jpg", 600, 350);
//FileStream fs = new FileStream(PicPath, FileMode.Open, FileAccess.Read);
//byte[] bytes = new byte[fs.Length];
//fs.Read(bytes, 0, bytes.Length);
//fs.Close();
//MemoryStream ms = new MemoryStream(bytes);
//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
//Response.ContentType = "image/jpg";
//Response.Write(img);
//Response.Write("<img src="+PicPath +"/>");
}
/// <summary>
/// 当报表数据更新时,先强制结束前一个报表的数据源
/// 这种方法会同时杀死掉用户的excel进程
/// </summary>
protected void EndExcelProcesse()
{
try
{
Process[] myProcesses = Process.GetProcessesByName("excel");
foreach (Process instance in myProcesses)
{
instance.Kill(); //强制终止
}
}
catch { }
}
/*
* 用Response.Write在页面显示时,页面卸载时删除.xls文件
protected void Page_UnLoad(object sender, EventArgs e)
{
EndExcelProcesse();
string FileName = Server.MapPath("~") + "\\Temp.xls";
if (File.Exists(FileName))
{
File.Delete(FileName);
}
}
*/
}
ASPX文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Output.aspx.cs" Inherits="Output" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label><p/>
<object classid="clsid:0002E559-0000-0000-C000-000000000046" width="600" id="Spreadsheet1" height="200" align ="middle">
<param name="DataType" value="HTMLURL"/>
<param name="HTMLURL" value="<%=FileName%>"/>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td bgcolor="#336699" height="25" width="10%"> </td>
<td bgcolor="#666666" width="85%">
<font face="宋体" color="white" size="4">
<b> 缺少 Microsoft Office Web Components</b>
</font>
</td>
</tr>
<tr>
<td bgcolor="#cccccc" width="15"> </td><td bgcolor="#cccccc" width="500px"><br>
<font face="宋体" size="2">此网页要求 Microsoft Office Web Components。
<p align="center">
<a href="C:/IUware Online/Microsoft Office Professional Enterprise Edition 2003/files/owc11/setup.exe"> 单击此处安装 Microsoft Office Web Components。
</a>.
</p>
</font>
<p>
<font face="宋体" size="2"> 此网页同时要求 Microsoft Internet Explorer 5.01 或更高版本。</p>
<p align="center"/><a href="http://www.microsoft.com/windows/ie/default.htm"> 单击此处安装最新的 Internet Explorer</a>.
</font><br>
</td>
</tr>
</table>
</object>
<p />
<img src="test.jpg"" alt="OWC图表例子!" />
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label><p/>
<object classid="clsid:0002E559-0000-0000-C000-000000000046" width="600" id="Spreadsheet1" height="200" align ="middle">
<param name="DataType" value="HTMLURL"/>
<param name="HTMLURL" value="<%=FileName%>"/>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td bgcolor="#336699" height="25" width="10%"> </td>
<td bgcolor="#666666" width="85%">
<font face="宋体" color="white" size="4">
<b> 缺少 Microsoft Office Web Components</b>
</font>
</td>
</tr>
<tr>
<td bgcolor="#cccccc" width="15"> </td><td bgcolor="#cccccc" width="500px"><br>
<font face="宋体" size="2">此网页要求 Microsoft Office Web Components。
<p align="center">
<a href="C:/IUware Online/Microsoft Office Professional Enterprise Edition 2003/files/owc11/setup.exe"> 单击此处安装 Microsoft Office Web Components。
</a>.
</p>
</font>
<p>
<font face="宋体" size="2"> 此网页同时要求 Microsoft Internet Explorer 5.01 或更高版本。</p>
<p align="center"/><a href="http://www.microsoft.com/windows/ie/default.htm"> 单击此处安装最新的 Internet Explorer</a>.
</font><br>
</td>
</tr>
</table>
</object>
<p />
<img src="test.jpg"" alt="OWC图表例子!" />
</form>
</body>
</html>
四、缺点:
客户端必须安装 Microsoft Office Web Components,它可随 Office 2003 一起安装,如果用户的公司具有 Office 2003 站点许可证,则可以通过公司的 Intranet 下载 Office Web 组件,用户还必须使用 Microsoft Internet Explorer 5.01 (Service Pack 2) 或更高版本。