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"; ...
随机推荐
- HTML标记语言
一.html的文档结构 html含义为超文本标记语言,html文档重要由4个标签来组成就是<html> <head> <title> <body> ...
- Ubuntu 16.04 环境下配置apache2.4 + php5.6
相信用惯了Windows的朋友一开始接触Linux是很崩溃的,因为很多东西都是通过命令行来完成的,包括安装绝大多数的开发工具以及环境,那么在Ubuntu下其实可以直接通过apt-get指令来安装apa ...
- PAT乙级考前总结(三)
特殊题型 1027 打印沙漏 (20 分) 题略,感觉有点像大学里考试的题.找规律即可. #include <stdio.h>#include <iostream>using ...
- HQL包含中文查询失败
jdbc:mysql://172.16.9.6:3306/school?useUnicode=true&characterEncoding=UTF-8配置文件中的url加上编码,一般mysql ...
- JavaScript 查找图中连接两点的所有路径算法
1.把图看成以起点为根节点的树 2.使用深度遍历算法遍历路径 3.遍历到节点为目标节点时,保存这条路径 find2PointsPath(sourceId, targetId) { const { no ...
- 芯灵思Sinlinx A64 linux 通过设备树写LED驱动(附参考代码,未测试)
开发平台 芯灵思Sinlinx A64 内存: 1GB 存储: 4GB 详细参数 https://m.tb.cn/h.3wMaSKm 开发板交流群 641395230 全志A64设备树结构体 #inc ...
- 公司内网接口ip城市查询分析
require 'rubygems' require 'json' print ARGV print "fist is :",ARGV[0] logfile="#{ARG ...
- 目标文件obj的各段 2
#程序的自我修养 page68
- Flutter Inspector 功能:Toggle Platform,Show Debug Paint,Show Paint Baselines
Flutter Inspector 功能 说明 Toggle Platform 切换操作系统(Android.iOS) Show Debug Paint Show Paint Baselines Wi ...
- Window服务项目脚手架
本人最近工作用到window服务程序,于是尝试分享下经验,开源了一个window服务脚手架项目,把window服务程序必不可少的组件集成进去,如日志组件log4net,window服务挂在后台,用日志 ...