轉(zhuǎn)自http://martinyang2010.bokee.com/2598999.html
using system;
using system.data;
using system.drawing;
using system.data.sqlclient;
using excel;
using word;
using system.io;
namespace common
{
/// <summary>
/// 把數(shù)據(jù)導(dǎo)入到.doc、.txt、.xls文件中
/// </summary>
public class export
{
private const string datawordpath = @"c:/folder/doc/datadoc/";
private const string imagewordpath = @"c:/folder/doc/imagedoc/";
private const string imagepath = @"c:/folder/image/";
private const string excelpath = @"c:/folder/excel/";
private const string txtpath = @"c:/folder/txt/";
private const string imagepostfix = ".bmp";
private const string wordpostfix = ".doc";
private const string excelpostfix = ".xls";
private const string txtpostfix = ".txt";
private const int datadistance = 5;
private const int tabdistance = 8;
public export()
{
//
// todo: 在此處添加構(gòu)造函數(shù)邏輯
//
}
/// <summary>
/// 獲得數(shù)據(jù)集dataset--------------------------------用于調(diào)試
/// </summary>
/// <returns>dataset</returns>
public dataset getdata()
{
try
{
string sconnectionstring;
sconnectionstring = "workstation id=guofu;packet size=4096;user id=sa;data source=guofu;persist security info=true;initial catalog=yc;password=sc";
sqlconnection objconn = new sqlconnection(sconnectionstring);
objconn.open();
sqldataadapter dapoint = new sqldataadapter("select * from point", objconn);
dataset dsyc = new dataset("yc");
dapoint.fillschema(dsyc,schematype.mapped, "point");
dapoint.fill(dsyc,"point");
dapoint = new sqldataadapter("select * from employee", objconn);
dapoint.fillschema(dsyc,schematype.mapped, "employee");
dapoint.fill(dsyc,"employee");
return dsyc;
}
catch(exception ex)
{
throw new exception(ex.message);
}
}
/// <summary>
/// 把數(shù)據(jù)文件導(dǎo)入到.xls文件
/// </summary>
/// <param name="ds"></param>
public void exporttoexcel(dataset ds)
{
if(ds.tables.count!=0)
{
//生成.xls文件完整路徑名
string tempfilename = gettempfilename();
object filename = excelpath+tempfilename+excelpostfix;
object nothing = system.reflection.missing.value;
//創(chuàng)建excel文件,文件名用系統(tǒng)時間生成精確到毫秒
excel.application myexcel = new excel.applicationclass();
myexcel.application.workbooks.add(nothing);
try
{
//把dataset中的數(shù)據(jù)插入excel文件中
int totalcount = 0;
for(int k =0;k<ds.tables.count;k++)
{
int row = ds.tables[k].rows.count;
int column = ds.tables[k].columns.count;
for(int i = 0;i<column;i++)
{
myexcel.cells[totalcount+2,1+i] = ds.tables[k].columns[i].columnname;
}
for(int i = 0;i<row;i++)
{
for(int j =0;j<column;j++)
{
myexcel.cells[totalcount+3+i,1+j] = "'" + ds.tables[k].rows[i][j].tostring();
}
}
totalcount = totalcount + row +4;
}
try
{
//保存excel文件到指定的目錄下,文件名用系統(tǒng)時間生成精確到毫秒
myexcel.activeworkbook._saveas(filename,nothing,nothing,nothing,nothing,nothing,xlsaveasaccessmode.xlexclusive,nothing,nothing,nothing,nothing);
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+excelpath+tempfilename+excelpostfix);
return;
}
//讓生成的excel文件可見
myexcel.visible = true;
}
catch(exception e)
{
system.windows.forms.messagebox.show("向excel文件中寫入數(shù)據(jù)出錯: " + e.message);
}
}
else
{
system.windows.forms.messagebox.show("no data");
}
}
/// <summary>
/// 把數(shù)據(jù)導(dǎo)入到.doc文件
/// </summary>
/// <param name="ds"></param>
public void exporttoword(dataset ds)
{
if(ds.tables.count!=0)
{
string tempfilename = null;
object filename = null;
object tablebehavior = word.wddefaulttablebehavior.wdword9tablebehavior;
object autofitbehavior = word.wdautofitbehavior.wdautofitfixed;
object unit = word.wdunits.wdstory;
object extend = system.reflection.missing.value;
object breaktype = (int)word.wdbreaktype.wdsectionbreaknextpage;
object count = 1;
object character = word.wdunits.wdcharacter;
object nothing = system.reflection.missing.value;
try
{
tempfilename = gettempfilename();
//生成.doc文件完整路徑名
filename = datawordpath+tempfilename+wordpostfix;
//創(chuàng)建一個word文件,文件名用系統(tǒng)時間生成精確到毫秒
word.application myword= new word.applicationclass();
word._document mydoc = new word.documentclass();
mydoc = myword.documents.add(ref nothing,ref nothing,ref nothing,ref nothing);
mydoc.activate();
//向把dataset中的表插入到word的文件中
for(int totaltable = 0;totaltable<ds.tables.count;totaltable++)
{
myword.application.selection.typetext(ds.tables[totaltable].tablename+"表的數(shù)據(jù)如下");
myword.application.selection.typeparagraph();
myword.application.selection.typeparagraph();
word.range para = myword.application.selection.range;
mydoc.tables.add(para,ds.tables[totaltable].rows.count+1,ds.tables[totaltable].columns.count,ref tablebehavior,ref autofitbehavior);
for(int column = 0; column<ds.tables[totaltable].columns.count;column++)
{
mydoc.tables.item(totaltable+1).cell(1,column+1).range.insertbefore(ds.tables[0].columns[column].columnname.trim());
}
for(int row = 0;row<ds.tables[totaltable].rows.count;row++)
{
for(int column = 0;column<ds.tables[totaltable].columns.count;column++)
{
mydoc.tables.item(totaltable+1).cell(row+2,column+1).range.insertbefore(ds.tables[totaltable].rows[row][column].tostring().trim());
}
}
myword.application.selection.endkey(ref unit,ref extend);
myword.application.selection.typeparagraph();
myword.application.selection.typeparagraph();
myword.application.selection.insertbreak(ref breaktype);
}
myword.application.selection.typebackspace();
myword.application.selection.delete(ref character,ref count);
myword.application.selection.homekey(ref unit,ref extend);
//保存word文件到指定的目錄下
try
{
mydoc.saveas(ref filename,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing);
myword.visible = true;
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+datawordpath+tempfilename+wordpostfix);
return;
}
//讓生成的excel文件可見
myword.visible = true;
}
catch(exception ex)
{
system.windows.forms.messagebox.show("向word文件中寫入數(shù)據(jù)出錯: " + ex.message);
}
}
else
{
system.windows.forms.messagebox.show("no data");
}
}
/// <summary>
/// 把圖片文件導(dǎo)入到.doc文件
/// </summary>
/// <param name="bp"></param>
public void exporttoword(bitmap bp)
{
string tempfilename = null;
string bmppath = null;
object filename = null;
object nothing = null;
tempfilename = gettempfilename();
//生成.bmp文件完整路徑名
bmppath = imagepath+tempfilename+imagepostfix;
//生成.doc文件完整路徑名
filename = imagewordpath+tempfilename+wordpostfix;
nothing = system.reflection.missing.value;
//創(chuàng)建一個word文件,文件名用系統(tǒng)時間生成精確到毫秒
word.application myword= new word.applicationclass();
word._document mydoc = new word.documentclass();
mydoc = myword.documents.add(ref nothing,ref nothing,ref nothing,ref nothing);
try
{
//把bitmap對象保存到系統(tǒng)所生成文件完整路徑中
bp.save(bmppath);
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+bmppath);
return;
}
try
{
//往word文件中插入圖片
mydoc.inlineshapes.addpicture(bmppath,ref nothing,ref nothing,ref nothing);
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+bmppath);
return;
}
try
{
//保存word文件到指定的目錄下
mydoc.saveas(ref filename,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing,ref nothing);
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+imagewordpath+tempfilename+wordpostfix);
return;
}
//讓生成的word文件可見
myword.visible = true;
}
/// <summary>
/// 把數(shù)據(jù)文件導(dǎo)入到.txt文件
/// </summary>
/// <param name="ds"></param>
public void exporttotxt(dataset ds)
{
if(ds.tables.count!=0)
{
string tempfilename = null;
tempfilename = gettempfilename();
//創(chuàng)建一個.txt文件,文件名用系統(tǒng)時間生成精確到毫秒
fileinfo file = new fileinfo(txtpath+tempfilename+txtpostfix);
streamwriter textfile = null;
try
{
textfile = file.createtext();
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+txtpath+tempfilename+txtpostfix);
return;
}
//把dataset中的數(shù)據(jù)寫入.txt文件中
for(int totaltable = 0;totaltable<ds.tables.count;totaltable++)
{
//統(tǒng)計dataset中當(dāng)前表的行數(shù)
int row = ds.tables[totaltable].rows.count;
//統(tǒng)計dataset中當(dāng)前表的列數(shù)
int column = ds.tables[totaltable].columns.count;
//用于統(tǒng)計當(dāng)前表中每列記錄中字符數(shù)最長的字符串的長度之和
int totallength = 0;
//用于統(tǒng)計標(biāo)題的長度(dataset中的表名的length+"表的數(shù)據(jù)如下"的length)
int titlelength = 0;
//統(tǒng)計每列記錄中字符數(shù)最長的字符串的長度
int[] columnlength = new int[column];
for(int i = 0;i<column;i++)
{
columnlength[i] = ds.tables[totaltable].columns[i].columnname.tostring().length;
}
for(int i = 0;i<row;i++)
{
for(int j = 0;j<column;j++)
{
if(ds.tables[totaltable].rows[i][j].tostring().length>columnlength[j])
{
columnlength[j]=ds.tables[totaltable].rows[i][j].tostring().length;
}
}
}
//統(tǒng)計當(dāng)前表中每列記錄中字符數(shù)最長的字符串的長度之和
for(int i = 0;i<column;i++)
{
totallength = totallength+columnlength[i]+datadistance;
}
totallength = totallength+2*tabdistance-datadistance;
//統(tǒng)計標(biāo)題的長度(dataset中的當(dāng)前表名的length+"表的數(shù)據(jù)如下"的length)
titlelength = ds.tables[totaltable].tablename.tostring().length+"表的數(shù)據(jù)如下".length*2;
//把標(biāo)題寫入.txt文件中
for(int i = 0;i<(int)((totallength-titlelength)/2);i++)
{
textfile.write(' ');
}
textfile.write(ds.tables[totaltable].tablename+"表的數(shù)據(jù)如下");
textfile.writeline();
for(int i = 0;i<totallength;i++)
{
textfile.write('*');
}
textfile.writeline();
textfile.write("/t");
//把dataset中當(dāng)前表的字段名寫入.txt文件中
for(int i = 0;i<column;i++)
{
textfile.write(ds.tables[totaltable].columns[i].columnname.tostring());
for(int k = 0;k<columnlength[i]-ds.tables[totaltable].columns[i].columnname.tostring().length+datadistance;k++)
{
textfile.write(' ');
}
}
textfile.writeline();
for(int i = 0;i<totallength;i++)
{
textfile.write('-');
}
textfile.writeline();
textfile.write("/t");
//把dataset中當(dāng)前表的數(shù)據(jù)寫入.txt文件中
for(int i = 0;i<row;i++)
{
for(int j = 0;j<column;j++)
{
textfile.write(ds.tables[totaltable].rows[i][j].tostring());
for(int k = 0;k<columnlength[j]-ds.tables[totaltable].rows[i][j].tostring().length+datadistance;k++)
{
textfile.write(' ');
}
}
textfile.writeline();
textfile.write("/t");
}
textfile.writeline();
for(int i = 0;i<totallength;i++)
{
textfile.write('-');
}
textfile.writeline();
textfile.writeline();
textfile.writeline();
}
//關(guān)閉當(dāng)前的streamwriter流
textfile.close();
system.windows.forms.messagebox.show("數(shù)據(jù)文件已保存到"+" "+file.fullname);
}
else
{
system.windows.forms.messagebox.show("no data");
}
}
public string gettempfilename()
{
return datetime.now.tostring("yyyymmddhhmmssfff");
}
}
}
補(bǔ)充:使用以上方法必須對dcom進(jìn)行配置,給用戶使用office的權(quán)限。
具體配置方法如下:
1:在服務(wù)器上安裝office的excel軟件.
2:在"開始"->"運(yùn)行"中輸入dcomcnfg.exe啟動"組件服務(wù)"
3:依次雙擊"組件服務(wù)"->"計算機(jī)"->"我的電腦"->"dcom配置"
4:在"dcom配置"中找到"microsoft excel 應(yīng)用程序",在它上面點擊右鍵,然后點擊"屬性",彈出"microsoft excel 應(yīng)用程序?qū)傩?對話框
5:點擊"標(biāo)識"標(biāo)簽,選擇"交互式用戶"
6:點擊"安全"標(biāo)簽,在"啟動和激活權(quán)限"上點擊"自定義",然后點擊對應(yīng)的"編輯"按鈕,在彈出的"安全性"對話框中填加一個"network service"用戶(注意要選擇本計算機(jī)名),并給它賦予"本地啟動"和"本地激活"權(quán)限.
7:依然是"安全"標(biāo)簽,在"訪問權(quán)限"上點擊"自定義",然后點擊"編輯",在彈出的"安全性"對話框中也填加一個"network service"用戶,然后賦予"本地訪問"權(quán)限.
這樣,我們便配置好了相應(yīng)的excel的dcom權(quán)限.
注意:我是在win2003上配置的,在2000上,是配置aspnet用戶
若不進(jìn)行配置會出現(xiàn)錯誤
檢索 com 類工廠中 clsid 為 {00024500-0000-0000-c000-000000000046} 的組件時失敗,原因是出現(xiàn)以下錯誤: 80070005。
原因是用戶沒有使用excel的權(quán)限。
導(dǎo)出到word同樣要配置使用word的權(quán)限。
繼續(xù)補(bǔ)充: 導(dǎo)出到txt我用了上面的方法有問題,
try
{
textfile = file.createtext();
}
catch
{
system.windows.forms.messagebox.show("系統(tǒng)找不到指定目錄下的文件: "+txtpath+tempfilename+txtpostfix);
return;
}
總是在這里跳到catch里面。導(dǎo)出到word,excel都能用,繼續(xù)研究txt的使用方法。
新聞熱點
疑難解答
圖片精選