datagridview 导出成WORD时问题,反复看过代码没有问题,求解!
在导出至WORD档是一直出错:未将对象引用设置到对象的实例 但是导出EXCEL的时候没有问题.我个人觉得是不是生成 WORD.TABLE的时候出现了问题下面是代码,请帮我看看
:
private void button1_Click(object sender, EventArgs e)
{
if(radioButton1.Checked==true)
{
saveFileDialog1.Filter = "WORD(*.DOCX)|*.DOC";
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
object savePath=saveFileDialog1.FileName;
Object onoe = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordApp =
new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document =
wordApp.Documents.Add(ref onoe, ref onoe, ref onoe, ref onoe);
try
{
Microsoft.Office.Interop.Word.Table table =
document.Tables.Add(document.Paragraphs.Last.Range, dataGridView1.Rows.Count,
dataGridView1.Columns.Count, ref onoe, ref onoe);
wordApp.Visible = false;
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
table.Cell(1, i + 1).Range.Text = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int y = 0; y < dataGridView1.Columns.Count; y++)
{
table.Cell(i + 2, y + 1).Range.Text = dataGridView1[y, i].Value.ToString();
}
}
document.SaveAs(ref savePath, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe, ref onoe);
document.Close(ref onoe, ref onoe, ref onoe);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
wordApp.Quit();
}
}
}
else
{
saveFileDialog1.Filter = "Excel(*.xlsx)|*.xls";
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
object savePath = saveFileDialog1.FileName;
Microsoft.Office.Interop.Excel.Application excel =
new Microsoft.Office.Interop.Excel.Application();
try
{
excel.DisplayAlerts = false;
excel.Workbooks.Add(true);
//excel.Visible = false;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
excel.Cells[2, i + 1] = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int y = 0; y < dataGridView1.Columns.Count; y++)
{
excel.Cells[i + 3, y + 1] = dataGridView1[y,i].Value;
}
}
excel.Workbooks[1].SaveCopyAs(savePath);
MessageBox.Show("文件保存成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
}
}
}