导出到Excel方法
public bool ExportDataGridviewExcel(DataGridView gridview,bool isShowExcel)
{
if (gridview.Rows.Count==0)
{
return false;
}
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcel;
//生成字段名称
for (int i = 0; i < gridview.Columns.Count; i++)
{
excel.Cells[1, i + 1] = gridview.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridview.Rows.Count-1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
if (gridview[j,i].ValueType==typeof(string))
{
excel.Cells[i+2,j+1]=""+gridview[j,i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridview[j, i].Value.ToString();
}
}
}
return true;
}
导出到Word方法
//导出到Word方法
public bool ExportDataGridviewWord(DataGridView gridview, bool isShowExcel)
{
if (gridview.Rows.Count == 0)
{
return false;
}
Word.Document mydoc = new Word.Document();
Word.Table mytable;
Word.Selection mysel;
Object myobj;
//建立Word对象
Word.Application word = new Word.Application();
myobj = System.Reflection.Missing.Value;
mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
word.Visible = isShowExcel;
mydoc.Select();
mysel = word.Selection;
//将数据生成Word表格文件
mytable = mydoc.Tables.Add(mysel.Range, this.dataGridView1.RowCount, this.dataGridView1.ColumnCount, ref myobj, ref myobj);
//设置列宽
mytable.Columns.SetWidth(30, Word.WdRulerStyle.wdAdjustNone);
//输出列标题数据
for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
{
mytable.Cell(1, i + 1).Range.InsertAfter(this.dataGridView1.Columns[i].HeaderText);
}
//输出控件中的记录
for (int i = 0; i < this.dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j < this.dataGridView1.ColumnCount; j++)
{
mytable.Cell(i + 2, j + 1).Range.InsertAfter(this.dataGridView1[j, i].Value.ToString());
}
}
return true;
}