代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
excel导出datdagridview 含图片列(必须有图片绝对路
作者:
Dezai.CN
/ 发布于
2013/1/4
/
739
页面的执行代码 /// <summary> /// 绑定数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button9_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("图片名称",typeof(string)); dt.Columns.Add("图片",typeof(Image)); dt.Columns.Add("ImagePath", typeof(string)); DataRow dr = dt.NewRow(); dr["图片名称"] = "1"; dr["图片"] = Image.FromFile("c://a4.png"); //图片路径 dr["ImagePath"] = "c://a4.png"; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr1["图片名称"] = "2"; dr1["图片"] = Image.FromFile("c://a3.png"); dr1["ImagePath"] = "c://a3.png"; dt.Rows.Add(dr1); dataGridView1.DataSource = dt; dataGridView1.Columns[2].Visible = false; } /// <summary> /// excel导出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button10_Click(object sender, EventArgs e) { Int32 iExcelType = -1; iExcelType = FuncCommon.ExistsRegedit(); if (!FuncCommon.CodeboolisExcelInstalled() && iExcelType <= 0) { MessageBox.Show("没有安装excel"); return; } SaveFileDialog sfdFile = new SaveFileDialog(); //wy add 2012.2.15 //默认文件后缀 if (iExcelType == 1) { sfdFile.DefaultExt = ".xls"; //文件后缀列表 sfdFile.Filter = "Excel文件(*.xls)|*.xls"; } else if (iExcelType == 2) { sfdFile.DefaultExt = ".xlsx"; //文件后缀列表 sfdFile.Filter = "Excel文件(*.xlsx)|*.xlsx"; } if (iExcelType == -1) { return; } ///end if (sfdFile.ShowDialog() != DialogResult.OK) { return; } string strSaveFile = sfdFile.FileName.ToString(); File.Delete(strSaveFile); if (File.Exists(strSaveFile)) { //m_dialog.ShowmyDialog(ConstInfo.STR_SAVEFAIL, "", false); return; } string _strCaption = ""; _strCaption = "测试导出图片列"; Int32 iRet = FuncCommon.ExportExcel(_strCaption, dataGridView1, strSaveFile); if (iRet == 0) { MessageBox.Show("成功导出"); } else { MessageBox.Show("失败导出"); } } excel导出类: using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Windows.Forms; using System.IO; using Microsoft.Win32; using System.Drawing; namespace ExerciseForm2 { public class FuncCommon { #region 判断是否安装excel /// <summary> /// 判断是否安装excel /// </summary> /// <returns></returns> public static bool CodeboolisExcelInstalled() { Type type = null; type = Type.GetTypeFromProgID("Microsoft.Office.Interop.Excel.Application"); return type != null; } #endregion #region Self_Variable:查询注册表某个键值是否存在 /// <summary> /// Self_Variable:查询注册表某个键值是否存在 /// </summary> /// <returns></returns> public static Int32 ExistsRegedit() { Int32 iExcelType = -1; RegistryKey rk = Registry.LocalMachine; RegistryKey akey = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Word\\InstallRoot\\"); RegistryKey akeytwo = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Word\\InstallRoot\\"); //检查本机是否安装Office2003 if (akey != null) { string file03 = akey.GetValue("Path").ToString(); if (File.Exists(file03 + "Excel.exe")) { iExcelType = 1; } } //检查本机是否安装Office2007 if (akeytwo != null) { string file07 = akeytwo.GetValue("Path").ToString(); if (File.Exists(file07 + "Excel.exe")) { iExcelType = 2; } } return iExcelType; } #endregion #region 将记录导出到Exel文档 /// <summary> /// DataGridView导出Excel /// </summary> /// <param name="strCaption">Excel文件中的标题</param> /// <param name="myDGV">DataGridView 控件</param> /// <returns>0:成功;1ataGridView中无记录;2:Excel无法启动;9999:异常错 误</returns> public static int ExportExcel(string strCaption, DataGridView myDGV, string strSaveFile) { int result = 9999; // 列索引,行索引,总列数,总行数 int ColIndex = 0; int RowIndex = 0; int ColCount = 0; int RowCount = myDGV.RowCount; if (myDGV.RowCount == 0) { result = 1; } // 创建Excel对象 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); if (xlApp == null) { result = 2; } try { foreach (DataGridViewColumn col in myDGV.Columns) { if (col.Visible) { ColCount += 1; } } // 创建Excel工作薄 Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1]; // 设置标题 Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同 range.MergeCells = true; xlApp.ActiveCell.FormulaR1C1 = strCaption; xlApp.ActiveCell.Font.Size = 20; xlApp.ActiveCell.Font.Bold = true; xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; // 创建缓存数据 object[,] objData = new object[RowCount + 1, ColCount]; //获取列标题 foreach (DataGridViewColumn col in myDGV.Columns) { //wy 2012.2.9 if (col.Visible) { objData[RowIndex, ColIndex++] = col.HeaderText; } } // 获取数据 RowIndex = 1; foreach (DataGridViewRow row in myDGV.Rows) { Int32 iIndex = 0; foreach (DataGridViewColumn col in myDGV.Columns) { if (col.Visible) { if (row.Cells[col.Index].ValueType == typeof(string) || row.Cells[col.Index].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓 存时在该内容前加入" "; { objData[RowIndex, iIndex++] = "" + row.Cells[col.Index].Value.ToString(); } else if (col.ValueType == typeof(Image)) { //的“+2”是比实际数据行多了标题与列名行 合起来多了两行 range = xlSheet.get_Range(xlApp.Cells[RowIndex+2, col.Index+1], xlApp.Cells[RowIndex+2, col.Index+1]); range.Select(); float PicLeft, PicTop; PicLeft = Convert.ToSingle(range.Left); PicTop = Convert.ToSingle(range.Top); Image img =(Image) row.Cells[col.Index].Value; DataGridViewColumn col1 = myDGV.Columns["ImagePath"]; xlSheet.Shapes.AddPicture(row.Cells[col1.Index].Value.ToString(), Microsoft.Office.Core.MsoTriState.msoTriStateToggle, Microsoft.Office.Core.MsoTriState.msoTriStateToggle, PicLeft, PicTop, 10, 10); } else { objData[RowIndex, iIndex++] = row.Cells[col.Index].Value.ToString(); } } } RowIndex++; System.Windows.Forms.Application.DoEvents(); } // 写入Excel 注:xlApp.Cells[RowCount + 2, ColCount] 的“+2”是比实际数据行多了标题与列名行 合起来多了两行 range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount + 2, ColCount]);//RowCount + 2 range.Value2 = objData; range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[RowCount + 2, ColCount]); range.Borders.LineStyle = 1; range.Columns.AutoFit(); foreach (DataGridViewColumn col in myDGV.Columns) { if (col.Visible) { if (col.ValueType == typeof(int) || col.ValueType == typeof(Int16) || col.ValueType == typeof(Int32) || col.ValueType == typeof(Int64)) { range = xlSheet.get_Range(xlApp.Cells[2, col.Index], xlApp.Cells[RowCount + 2, col.Index]);//RowCount + 2 range.NumberFormatLocal = "#"; } } } //保存 xlBook.Saved = true; //xlBook.SaveCopyAs(strSaveFile); xlBook.SaveAs(strSaveFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); //返回值 result = 0; } catch (Exception err) { result = 9999; } finally { xlApp.Quit(); GC.Collect(); //强制回收 } return result; } #endregion } }
试试其它关键字
导出datdagridview
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Dezai.CN
贡献的其它代码
(
4037
)
.
多线程Socket服务器模块
.
生成随机密码
.
清除浮动样式
.
弹出窗口居中
.
抓取url的函数
.
使用base HTTP验证
.
div模拟iframe嵌入效果
.
通过header转向的方法
.
Session操作类
.
执行sqlite输入插入操作后获得自动编号的ID
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3