小小的功能,刚学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);
}
}
}