首页
XP系统
Win7 系统
win8 系统
win10 系统
win11系统
系统教程
电脑教程
游戏攻略
当前位置:
系统之家
>
技术开发教程
>
详细页面
全部
安卓应用教程
办公软件教程
电脑学习教程
苹果应用教程
技术开发教程
网络软件教程
如何由DataSet将数据导入Excel?
更新时间:2022-10-31
文章作者:未知
信息来源:网络
阅读次数:次
/// <summary>
/// 将DataSet里所有数据导入Excel.
/// 需要添加COM: Microsoft Excel Object Library.
/// using Excel;
/// </summary>
/// <param name="filePath"></param>
/// <param name="ds"></param>
public static void ExportToExcel(string filePath, DataSet ds)
{
object oMissing = System.Reflection.Missing.Value;
Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
try
{
// 打开Excel文件。以下为Office 2000.
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing);
Excel.Worksheet xlWorksheet;
// 循环所有DataTable
for( int i=0; i<ds.Tables.Count; i++ )
{
// 添加入一个新的Sheet页。
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
// 以TableName作为新加的Sheet页名。
xlWorksheet.Name = ds.Tables[i].TableName;
// 取出这个DataTable中的所有值,暂存于stringBuffer中。
string stringBuffer = "";
for( int j=0; j<ds.Tables[i].Rows.Count; j++ )
{
for( int k=0; k<ds.Tables[i].Columns.Count; k++ )
{
stringBuffer += ds.Tables[i].Rows[j][k].ToString();
if( k < ds.Tables[i].Columns.Count - 1 )
stringBuffer += "\t";
}
stringBuffer += "\n";
}
// 利用系统剪切板
System.Windows.Forms.Clipboard.SetDataObject("");
// 将stringBuffer放入剪切板。
System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
// 选中这个sheet页中的第一个单元格
((Excel.Range)xlWorksheet.Cells[1,1]).Select();
// 粘贴!
xlWorksheet.Paste(oMissing,oMissing);
// 清空系统剪切板。
System.Windows.Forms.Clipboard.SetDataObject("");
}
// 保存并关闭这个工作簿。
xlWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
xlWorkbook = null;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// 释放...
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
GC.Collect();
}
}
温馨提示:喜欢本站的话,请收藏一下本站!
本类教程下载
1.C#语言初级基础(3)
2.繁体中文转换为简体中文的PHP函数
3.ASP.NET中数据库的设置初步----Data...
4.ASP.NET中动态更改web.config中的...
5.JSP基础图文详细教程(2)
6.用c写CGI 程序简要向导
7.基于数据库的在线人数,日访问量等统计
8.C#语言初级基础(2)
9.VB.NET完成DataList横向数据交替变色
10.PHP安装攻略:经常见问题回答(3)
系统下载排行
1.电脑公司Windows8.1 X64免激活专业版...
2.番茄花园windows xp万能装机版系统 20...
3.雨林木风Ghost Windows8.1 X32...
4.番茄花园Ghost Win10 (X64) 全新...
5.电脑公司 GHOST WIN7 32位安全稳定版...
6.番茄花园windows xp万能装机版系统 20...
7.深度技术 Ghost Win7 32位装机旗舰版...
8.系统之家Windows8.1 X32装机正式版系...
9.电脑公司 GHOST WIN7 64位安全稳定版...
10.windows 7 loader下载_windo...