C# 调用Excel组件生成excel文件

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
protected void exportToExcelClient(IDictionary < string , string > map)
{
if (map.Count == 0 )
{
MessageBox.Show(
" 请选择要导出的字段! " , " 提示 " , MessageBoxButtons.OK, MessageBoxIcon.Information);
return ;
}
pgbClient.Value
= 0 ;
_excel
= new Excel.Application();
Excel.Workbook wbook
= _excel.Workbooks.Add(Missing.Value);
Excel.Worksheet wsheet
= (Excel.Worksheet)_excel.ActiveSheet;
Excel.Range range
= (Excel.Range)wsheet.Cells;
Excel.Range ran
= null ;
string tofilepath = Application.StartupPath + " \\Excel_save\\ " ;
string tofilename = " customer.xls " ;
string sql = " SELECT " ;
ArrayList keyArr
= new ArrayList();
foreach (KeyValuePair < string , string > entry in map)
{
sql
+= entry.Value + " , " ;
keyArr.Add(entry.Key);
}
sql
= sql.Substring( 0 , sql.Length - 1 );
sql
+= " FROM tb_ClientInfo WHERE 1=1 " + condition;
// MessageBox.Show(sql);
DataSet myds = boperate.getds(sql, " tb_Client " );
DataTable dt
= myds.Tables[ " tb_Client " ];
for ( int i = 0 ; i < keyArr.Count; i ++ )
{
ran
= (Excel.Range)range[ 1 , i + 1 ];
ran.Font.Bold
= true ;
ran.Font.Size
= 10 ;
ran.Value2
= keyArr[i];
// ran.Columns.AutoFit();
NAR(ran);
pgbClient.Step
= 10 / keyArr.Count;
pgbClient.Value
+= 10 / keyArr.Count;
}
for ( int i = 0 ; i < dt.Rows.Count; i ++ )
{
for ( int j = 0 ; j < dt.Columns.Count; j ++ )
{
ran
= (Excel.Range)range[i + 2 , j + 1 ];
ran.Value2
= dt.Rows[i][j];
ran.Font.Size
= 10 ;
ran.Columns.AutoFit();
NAR(ran);
}
pgbClient.Step
= 90 / dt.Rows.Count;
pgbClient.Value
+= 90 / dt.Rows.Count;
}
if ( ! Directory.Exists(tofilepath))
{
Directory.CreateDirectory(tofilepath);
}
if (File.Exists(tofilepath + tofilename))
{
File.Delete(tofilepath
+ tofilename);
}
wbook.SaveAs(tofilepath
+ tofilename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbook.Close(
false , Type.Missing, Type.Missing);
NAR(range);
NAR(wsheet);
_excel.Quit();
NAR(_excel);
pgbClient.Value
= pgbClient.Maximum;
System.Threading.Thread.Sleep(
500 );
System.Diagnostics.Process.Start(
" EXCEL.EXE " ,tofilepath + tofilename);

// this.Close();
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="o"></param>
private void NAR( object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch { }
finally
{
o
= null ;
}
}

NAR方法用于释放资源 , exportToExcelClient方法的IDictionary<string, string> map字典结构用于根据用户所选的数据字段来导出到excel。就是这样,C#生成excel挺方便的,C/S , B/S都能用 。

转载于:https://www.cnblogs.com/sparemylife/archive/2010/06/19/1760719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值