從DataView中生成Excel報表的方案

前幾天一同事問我如何利用C#將數據導到Excel文件當中,當時比較忙沒有
顧得上去研究,今天特地研究了一下,基本搞定,下面就具體介紹如何將
DataView中的數據按照一定格式存到Excel文件當中。 <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> <iframe width="728" scrolling="no" height="90" frameborder="0" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2678127770746529&dt=1182765647125&lmt=1160458586&format=728x90_as&output=html&correlator=1182765645593&channel=8331943080&url=http%3A%2F%2Fwww.bbsjhw.com%2Fhtml%2F2006-02%2F204.htm&color_bg=FFFFFF&color_text=000000&color_link=000000&color_url=333333&color_border=FFFFFF&ad_type=text_image&ref=http%3A%2F%2Fwww.google.cn%2Fsearch%3Fcomplete%3D1%26hl%3Dzh-CN%26newwindow%3D1%26q%3DC%25232005%2BDataRowView%25E6%25A0%2587%25E9%25A2%2598%26btnG%3DGoogle%2B%25E6%2590%259C%25E7%25B4%25A2%26meta%3Dlr%253Dlang_zh-CN&cc=100&flash=9&u_h=768&u_w=1024&u_ah=738&u_aw=1024&u_cd=32&u_tz=480&u_his=1&u_java=true&u_nplug=8&u_nmime=19" name="google_ads_frame"></iframe>
正文:
一、首先要引用一個Excel的組件,我一開始是在Office XP下嘗試的,不
成功,後來把XP給幹掉,裝2k,就成功了,所以這裏分享的是Office 2k下
引用相關組件來實現功能的,在工程中引用COM標籤中的Microsoft 
Excel 9.0 Object Library,添加成功後,引用中會多出三個引用項:
Excel、Office、VBIDE。





二、具體代碼。
using System;
using System.Data;
using Excel;
using System.IO;
namespace Test.ExcelCom
{
/// <summary>
/// 將DataView中的數據導入Excel文件中
/// 作者:Rexsp
/// 創建:2004-4-4
/// </summary>
public class OutputExcel
{
#region 私有成員
/// <summary>
/// 數據的DataView
/// </summary>
private DataView dv=null;
/// <summary>
/// 表格標題
/// </summary>
private string title=null;
/// <summary>
/// 輸出文件路徑
/// </summary>
private string outFilePath=null;
/// <summary>
/// 輸入文件名
/// </summary>
private string inputFilePath=null;
#endregion
#region 公共屬性
/// <summary>
/// 數據的DataView
/// </summary>
public DataView DV
{
set{dv=value;}
}
/// <summary>
/// 表格標題
/// </summary>
public string Title
{
set{title=value;}
get{return title;}
}
/// <summary>
/// 輸出文件路徑
/// </summary>
public string OutFilePath
{
set{outFilePath=value;}
get{return outFilePath;}
}
/// <summary>
/// 輸入文件路徑
/// </summary>
public string InputFilePath
{
set{inputFilePath=value;}
get{return inputFilePath;}
}
#endregion

#region 構造函數
public OutputExcel()
{
}
public OutputExcel(DataView dv,string title)
{
//
// TODO: 在此處添加構造函數邏輯
//
}
#endregion
#region 公共方法
public void CreateExcel()
{
int rowIndex=4;//行起始座標
int colIndex=1;//列起始座標
ApplicationClass myApp=null;
Workbook myBook=null;
Worksheet mySheet=null;
//如果文件不存在,則將模板文件拷貝一份作爲輸出文件
//這裏如果通過File.Create來創建文件是不行的,因爲xls
//的空文件也有固定的格式,跟文本不一樣的,也許有其它
//通過程序直接生成excel的方法,大家可以嘗試嘗試的
if(!File.Exists(outFilePath))
{
File.Copy(inputFilePath,outFilePath,true);
}
myApp= new ApplicationClass();
myApp.Visible=false;
object oMissiong=System.Reflection.Missing.Value;
myApp.Workbooks.Open(outFilePath,oMissiong,oMissiong,oMissiong,oMissiong,
oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong);
myBook=myApp.Workbooks[1];
mySheet=(Worksheet)myBook.ActiveSheet;

//
//取得標題
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
mySheet.Cells[4,colIndex] = col.ColumnName;
mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
//設置標題格式爲居中對齊
}
//
//取得表格中的數據
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
mySheet.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
mySheet.get_Range (mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment  = XlVAlign.xlVAlignCenter;//設置日期型的字段格式爲居中對齊
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
mySheet.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
mySheet.get_Range (mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment  = XlVAlign.xlVAlignCenter;//設置字符型的字段格式爲居中對齊
}
else
{
mySheet.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加載一個合計行
//
int rowSum = rowIndex + 1;
int colSum = 2;
mySheet.Cells[rowSum,2] = "合計";
mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//設置選中的部分的顏色
//
mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Select();
mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//設置爲淺黃色,共計有56種
//
//取得整個報表的標題
//
mySheet.Cells[2,2] = title;
//
//設置整個報表的標題格式
//
mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Bold = true;
mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Size = 22;
//
//設置報表表格爲最適應寬度
//
mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Select();
mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//設置整個報表的標題爲跨列居中
//
mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).Select();
mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
//繪製邊框
//
mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
mySheet.get_Range (mySheet.Cells[4,2],mySheet.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft]. Weight = XlBorderWeight.xlThick;//設置左邊線加粗
mySheet.get_Range(mySheet.Cells [4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight  = XlBorderWeight.xlThick;//設置上邊線加粗
mySheet.get_Range(mySheet.Cells[4, colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight]. Weight = XlBorderWeight.xlThick;//設置右邊線加粗
mySheet.get_Range(mySheet.Cells [rowSum,2],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom]. Weight = XlBorderWeight.xlThick;//設置下邊線加粗
myBook.Save();;
myBook.Close( true,outFilePath,true);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp);
GC.Collect();

}
#endregion
}

}
一點說明:操作Excel的時候,可能會發生Excel進程被鎖定,無法退
出,解決方法是在保存完並關閉myBook(工作簿)後,別關閉Excel進
程(//myApp.Quit();)。這樣的結果是服務器上始終有一個Excel的
進程。可能會出現asp_net用戶操作Excel的權限不夠,配置Dcom。運
行Dcomcnfg.exe,找到Excel應用程序,配置其屬性,身份驗證級別
選"無",身份標識選"交互式用戶",安全性頁面,啓動和訪問均給
everyone。注意:查看當前進程中是否有Winword進程存在,如果有且
不能被結束,那麼重啓動計算機。再次運行你的代碼即OK。這樣以後
就不會出現權限不夠的情況了。
三、調用
#region 測試Excel
QuickItemCollection qic =new QuickItemCollection();
qic.GetAllInfo();
DataView dv= new DataView();
DataTable dt = new DataTable("Excel");
dt.Columns.Add("ID",System.Type.GetType("System.String"));
dt.Columns.Add("ItemName",System.Type.GetType("System.String"));
int qicCount=qic.Count;
for(int i=0;i<qicCount;i++)
{
DataRow dr= dt.NewRow();
dr[0] = qic[i].ID;
dr[1] = qic[i].ItemName;
dt.Rows.Add(dr);
}
OutputExcel ope = new OutputExcel(); 
ope.DV=dt.DefaultView;
ope.Title="測試生成Excel";
ope.InputFilePath=Server.MapPath("Sample.xls");
ope.OutFilePath=Server.MapPath("Test.xls");
ope.CreateExcel();
#endregion
一點說明:這段代碼的前半部分讀過我那篇《一種快速存取訂閱條目的方
案》的讀者應該認得的,其實也就是一個把集合類中數據填充到
DataView中的過程,後面的就是調用。Sample.xls是個新建的空的
Sample.xls,然後執行完畢後,就會生成Test.xls文檔 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章