| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2724 人关注过本帖, 1 人收藏
标题:把datagridview的数据输出为Excel,Word的简单应用
取消只看楼主 加入收藏
shenba
Rank: 1
等 级:新手上路
威 望:1
帖 子:179
专家分:0
注 册:2006-9-17
收藏(1)
 问题点数:0 回复次数:0 
把datagridview的数据输出为Excel,Word的简单应用

小小的功能,刚学office方面的编程

public static void ExportData(DataGridView srcDgv,string fileName)//导出数据,传入一个datagridview和一个文件路径
{
string type = fileName.Substring(fileName.IndexOf(".")+1);//获得数据类型


if (type.Equals("xls",StringComparison.CurrentCultureIgnoreCase))//Excel文档
{
Excel.Application excel = new Excel.Application();
try
{
excel.DisplayAlerts = false;
excel.Workbooks.Add(true);
excel.Visible = false;

for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
{
excel.Cells[2, i+1] = srcDgv.Columns[i].HeaderText;
}

for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < srcDgv.Columns.Count; j++)
{
excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;
}
}

excel.Workbooks[1].SaveCopyAs(fileName);//保存
}
finally
{
excel.Quit();
}
return;
}

//保存Word文件

if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))
{

object path = fileName;

Object none=System.Reflection.Missing.Value;
Word.Application wordApp = new Word.Application();
Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
//建立表格
Word.Table table= document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count+1, srcDgv.Columns.Count, ref none, ref none);

try
{

for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
{
table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
}

for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < srcDgv.Columns.Count; j++)
{

table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();
}
}

document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
document.Close(ref none, ref none, ref none);

}
finally
{
wordApp.Quit(ref none, ref none, ref none);
}

}

}

搜索更多相关主题的帖子: Excel datagridview Word 数据 应用 
2007-01-07 21:32
快速回复:把datagridview的数据输出为Excel,Word的简单应用
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012285 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved