博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 导出 不保存 直接显示
阅读量:6994 次
发布时间:2019-06-27

本文共 1571 字,大约阅读时间需要 5 分钟。

导出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, "提示");}}

  

转载于:https://www.cnblogs.com/zzzzbk/p/5888639.html

你可能感兴趣的文章