导入到excel:
Excel.Application excel = newExcel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] =this.dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < this.dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j <this.dataGridView1.ColumnCount; j++)
{
excel.Cells[i + 2, j + 1] =this.dataGridView1[j, i].Value.ToString();
}
}
导入到word:
Word.Document mydoc = new Word.Document();
Word.Table mytable;
Word.Selection mysel;
Object myobj;
//建立Word对象
Word.Application word = newWord.Application();
myobj = System.Reflection.Missing.Value;
mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
word.Visible = true;
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());
}
}