当前位置:
软件学习
>
Excel
>>
怎么由DataSet将数据导入Excel?
/// <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 += " ";
}
stringBuffer += " ";
}
// 利用系统剪切板
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();
}
}
补充:
Web开发 , ASP.Net ,
上一个:
Visual Basic串口通讯调试方法
下一个:
ASP.NET创建XML Web服务全接触(11)
更多图片编程知识:
Excel高效数据校验的两种方法
Office技巧:用好Excel强大的排序功能
Excel“自动求和”批处理功能
Excel 2002制作自动记录的单位考勤表
Excel基础知识如何导入或导出文本文件
用EXCEL轻松的准备考前工作
更多
Excel
疑问解答:
powerpoint的使用技巧
在Excel中实现中文大写数字
powerpoint演示文稿异地播放四步曲
word文档加密小技巧
学习Excel 2000入门操作
Excel:让你的图表更具魅力
Excel:快速输入数据
Excel:多班成绩快速统计
Excel:弹指之间输入特定文本
Excel:人民币小写金额转换大写技巧两则
Excel:单列表格的打印方法
Excel:轻松查看数据记录
开启Excel的自动保存功能
Excel中自定义函数实例剖析
Excel快速查找成绩表中出错的号码
站长资源库
Dreamweaver
Fireworks
FrontPage
Flash
Photoshop
Coreldraw
Excel
Word
Powerpoint
outlook
wps
AfterEffects
3D MAX
Director
Authorware
PremierePro
Foxmail
Maya
ISA
会声会影
其它软件
AutoCAD
如果你遇到
软件学习
难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答
www.zzzyk.com
All Rights Reserved
部份技术文章来自网络,