C# 导出 不保存 直接显示

<summary>
导出
</summary>
<param name="sender"></param>
<param name="e"></param>
private void btnExport_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("无数据可导出!", "提示");
return;
}
//建立Excel对象 

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
//生成字段名称 
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; 

}
Microsoft.Office.Interop.Excel.Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, 11]);
//字体加粗
range.Font.Bold = true;
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Color.Yellow.ToArgb()); //边框

//填充数据 
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (dataGridView1[j, i].Value.ToString() == null)
continue;
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView1[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}

}
}
excel.get_Range(excel.Cells[1, 1], excel.Cells[dataGridView1.RowCount, 11]).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Color.Yellow.ToArgb()); //边框

}
catch (Exception ex)
{
MessageBox.Show("导出失败:" + ex.Message, "提示");
}
}

  

posted on 2016-09-20 14:11  ningmou  阅读(461)  评论(0编辑  收藏  举报