winform datagridview 导出excel
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WebCrawl
{
class Excel
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static void ExportExcel( DataGridView myDGV)
{
if (myDGV.Rows.Count > 0)
{
string saveFileName = "";
//bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
//saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
//Microsoft.Office.Interop.Excel.Application _excelApplicatin = null;
//_excelApplicatin = new Microsoft.Office.Interop.Excel.Application();
//_excelApplicatin.Visible = true;
//_excelApplicatin.DisplayAlerts = true;
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Microsoft.Office.Interop.Excel.Range range;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.get_Range("A1","J1");
range.Select();
xlApp.ActiveWindow.SplitColumn = 0;
xlApp.ActiveWindow.SplitRow = 1;
xlApp.ActiveWindow.FreezePanes = true;
//xlApp.ActiveWindow.FreezePanes = true;
range.Font.Name = "微软雅黑";
range.Font.Size = 10;
range.WrapText = true;
range.EntireColumn.AutoFit();
range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
range.VerticalAlignment = XlVAlign.xlVAlignCenter; ;
//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
//写入数值
for (int r = 0; r < myDGV.Rows.Count-1; r++)
{
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
object Cell1="A"+(r+2)+"";
object Cell2="J"+(r+2)+"";
worksheet.get_Range(Cell1,Cell2).Font.Name = "微软雅黑";
worksheet.get_Range(Cell1,Cell2).Font.Size = 10;
worksheet.get_Range("C" + (r + 2) + "", "C" + (r + 2) + "").Font.Color = System.Drawing.Color.FromArgb(128, 0, 128).ToArgb();
//worksheet.get_Range("C" + (r + 2) + "", "C" + (r + 2) + "").Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
//worksheet.get_Range(Cell1, Cell2).WrapText = true;
worksheet.get_Range(Cell1, Cell2).HorizontalAlignment = XlHAlign.xlHAlignCenter;
worksheet.get_Range(Cell1, Cell2).VerticalAlignment = XlVAlign.xlVAlignCenter;
worksheet.get_Range(Cell1, Cell2).Borders.LineStyle = XlLineStyle.xlContinuous;
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
//if (Microsoft.Office.Interop.cmbxType.Text != "Notification")
//{
// Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);
// rg.NumberFormat = "00000000";
//}
if (saveFileName != "")
{
try
{
workbook.Saved = true;
//workbook.SaveCopyAs(saveFileName);
workbook.SaveAs(saveFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//fileSaved = true;
}
catch (Exception ex)
{
//fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
//else
//{
// fileSaved = false;
//}
xlApp.Quit();
GC.Collect();//强行销毁
Kill(xlApp);
// if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
}
else
{
return;
}
}
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{
IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
int k = 0;
GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
p.Kill(); //关闭进程k
}
}
}
winform datagridview 导出excel的更多相关文章
- 从DataGridView导出Excel
从DataGridView导出Excel的两种情况,不多说,直接记录代码(新建类,直接引用传入参数). using System; using System.Collections.Generic; ...
- c# datagridview导出Excel文件 问题
今天vs2010c#开发做datagridview导出Excel文件时,发现一个问题,和大家探讨一下: 第一种方式:写流的方式 private void button_Excel_Click(obje ...
- winform导入导出excel,后台动态添加控件
思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...
- 一个通用的DataGridView导出Excel扩展方法(支持列数据格式化)
假如数据库表中某个字段存放的值“1”和“0”分别代表“是”和“否”,要在DataGridView中显示“是”和“否”,一般用两种方法,一种是在sql中直接判断获取,另一种是在DataGridView的 ...
- C# DataGridView 导出 Excel(根据Excel版本显示选择不同后缀格式xls或xlsx)
/// <summary> /// DataGridView导出至Excel,解决问题:打开Excel文件格式与扩展名指定格式不一致 /// </summary> /// &l ...
- DataGridView 导出Excel (封装)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...
- 【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据
准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...
- winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏
public bool ExportDataGridview(DataGridView gridView) { if (gridView.Rows.Count ...
- [WinForm]dataGridView导出到EXCEL
方法一: SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; ...
随机推荐
- 总结React写参数的几种方式
1.在render方法内 class Text extends Component{ render(){ const data=[1,2,3]; return( { data.map((item,in ...
- ansible 下lineinfile详细使用
ansible 下lineinfile详细使用 时间 2016-12-13 18:02:31 51CTO推荐博文 原文 http://zouqingyun.blog.51cto.com/78224 ...
- 前端使用Mock服务Json-server
前言 由于Jaguar服务目前还没有任何的API输出,一边写前端功能,一边写后端API显然不利于整体的项目进展.所以我计划先定义好接口,然后将所有的API都先部署在一个Mock服务器上,等前端界面和功 ...
- Failed to load ApplicationContext ,Error creating bean with name 'adminUserService': Injection of autowired dependencies failed;
Druid配置的时候出现这个问题: "C:\Program Files\Java\jdk1.8.0_191\bin\java" -ea -Didea.test.cyclic.buf ...
- vue b表单
你可以用 v-model 指令在表单控件元素上创建双向数据绑定. v-model 会根据控件类型自动选取正确的方法来更新元素. 输入框 实例中演示了 input 和 textarea 元素中使用 v- ...
- 【笔记】 laravel 的路由
路由简介 : 请求对应着路由,将用户的请求转发给相应的程序进行处理 建立URL与程序之间的映射 Laravel中的请求类型:get.post.put.patch.delete Route::get ...
- C51单片机_day_01(定时器和中断系统)
c51单片机 51单片机是控制电路系统的开关,当然芯片就是51芯片,现在随着科技的发展,也是出了很多,功能更多,更全的芯片. 51是用c语言做为程序编程的语言 ——我对基本基础 ...
- lua 的 break
break ,退出最近的一层循环 return , 一般用于函数,会直接退出所有的循环,或者判断,返回参数 ,,,} for key,value in pairs(tb) do while(t ...
- Linux----------Openssh介绍以及用法
一.OpenSSH介绍 OpenSSH这一术语指系统中使用的Secure Shell软件的软件实施.用于在远程系统上安全运行shell.如果您在可提供ssh服务的远程Linux系统中拥有用户帐户,则s ...
- tomcat使用自签名证书实现https加密访问
部署好java环境和tomcat之后 执行以下语句 #生成证书,keytool是java工具命令,-genkey生成证书,-alias证书名称,-keyalg应该是指算法,-keystore是证书存储 ...