DataGridView如何快速导出Excel
从DataGridView或DataTable导出Excel文件,为了按照数据类型设置单元格格式,导出Excel时速度都比较慢,一直找不到好的办法。
最后从外文网站上找到解决办法,使用ws.get_Range(excelRange, Type.Missing).Value2方法批量设置单元格的值。详细代码如下:
public void DataToExcelFast(DataGridView dgv, string fName)
{
try
{
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.Workbooks.Add(true);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
ws.Name = fName;
string sFile = string.Empty;
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "Save export file";
dialog.Filter = "EXECL File(*.xlsx) |.xlsx";
dialog.FileName = fName;
dialog.FilterIndex = ;
if (dialog.ShowDialog() == DialogResult.OK)
{
string FileName = dialog.FileName;
if (File.Exists(FileName))
File.Delete(FileName);
sFile = FileName;
excel.Visible = false;
excel.DisplayAlerts = false;
excel.Calculation = Excel.XlCalculation.xlCalculationManual;
ArrayList cols = new ArrayList();
#region 列标题,并根据列的数据类型设置Excel列的格式
int visibleColumnCount = ;
foreach (DataGridViewColumn col in dgv.Columns)
{
if (col.Visible)
{
visibleColumnCount++;
ws.Cells[, visibleColumnCount].Value2 = col.HeaderText.ToString();
ws.Cells[, visibleColumnCount].Font.Bold = true;
cols.Add(col.Name);
if (col.ValueType != null)
{
if (col.ValueType.Name.Equals("DateTime"))
{
ws.Columns[visibleColumnCount].NumberFormatLocal = @"yyyy-mm-dd HH:mm";
ws.Columns[visibleColumnCount].Font.Color
= System.Drawing.ColorTranslator.ToOle(Color.Blue);
}
else if (col.ValueType.Name.Equals("Decimal")
|| col.ValueType.Name.Equals("Double"))
{
ws.Columns[visibleColumnCount].NumberFormat = "0.00";
}
else if (col.ValueType.Name.Equals("Int32"))
{
ws.Columns[visibleColumnCount].NumberFormat = "";
}
else
{
ws.Columns[visibleColumnCount].NumberFormatLocal = @"@";
}
}
else
ws.Columns[visibleColumnCount].NumberFormatLocal = @"@";
}
}
#endregion
#region 写入行
// Copy each DataTable
// Copy the DataTable to an object array
object[,] rawData = new object[dgv.Rows.Count, cols.Count];
// Copy the column names to the first row of the object array
for (int col = ; col < cols.Count; col++)
{
rawData[, col] = cols[col];
}
// Copy the values to the object array
for (int col = ; col < cols.Count; col++)
{
for (int row = ; row < dgv.Rows.Count; row++)
{
rawData[row, col] = dgv.Rows[row].Cells[cols[col].ToString()].Value;
}
}
// Calculate the final column letter
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (cols.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(cols.Count - ) / colCharsetLen - , );
}
finalColLetter += colCharset.Substring(
(cols.Count - ) % colCharsetLen, );
// Fast data export to Excel
string excelRange = string.Format("A2:{0}{1}",
finalColLetter, dgv.Rows.Count + );
ws.get_Range(excelRange, Type.Missing).Value2 = rawData;
#endregion
excel.Calculation = Excel.XlCalculation.xlCalculationAutomatic;
// 51表示2007-2010格式的xlsx
ws.SaveAs(FileName, , Type.Missing, Type.Missing,
Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing);
wb.Close(true, Type.Missing, Type.Missing);
excel.Quit();
// 安全回收进程
System.GC.GetGeneration(excel);
if (MessageBox.Show("已经导出Excel,您是否要打开?", "提示",
MessageBoxButtons.YesNo) == DialogResult.Yes)
System.Diagnostics.Process.Start(FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("导出Excel时遇到错误\r\n" + ex.Message,
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
DataGridView如何快速导出Excel的更多相关文章
- datagridview控件--导出Excel
dataGridView控件可以说很方便的显示了数据,而且对于修改和删除数据也很方便,我在前面的一篇博客中写到了如何去绑定数据到该控件上dataGridView控件--绑定数据方法,今天我将如何将数据 ...
- C# DataGridview用NPOI导出Excel文件
导出excel我用的是nuget 的NPOI,直接在项目中添加的,引用到项目中,下面是截图: 下面我把ExcelHelper贴出来 public static class ExcelHelper { ...
- asp.net mvc4使用NPOI 数据处理之快速导出Excel文档
一.背景 在之前做的小项目里有一需求是:要求将一活动录入的数据进行统计,并以excel表格形式导出来,并且对表格格式要求并不高. 二.问题分析 鉴于用户只要求最终将数据库中的数据导出excel,对于格 ...
- 使用Magicodes.IE快速导出Excel
前言 总是有很多朋友咨询Magicodes.IE如何基于ASP.NET Core导出Excel,出于从框架的体验和易用性的角度,决定对Excel的导出进行独立封装,以便于大家更易于使用,开箱即用. 注 ...
- 实现标记datagridview标题并导出Excel的功能
最近在学习winform,国庆前被布置了一个小任务,好不容易大致做出来了,决定记录下来,以此加深印象. 先说下需求:这是一个导入话单标记后并导出的功能 1. 选择excel文件 2. 定义字段 日 ...
- AX 利用windows粘贴板功能实现批量数据快速导出EXCEL
static void test(Args _args) { int lineNum; int titleLines; SysExcelApplication excel; SysExcelWorkb ...
- PHP快速导出Excel文件 (采用xlsx Writer)
<?php include_once("xlsxwriter.class.php"); ini_set('display_errors', 0); ini_set('log_ ...
- 利用PHPExcel快速导出excel
<?php $objPHPExcel = new PHPExcel(); $objSheet = $objPHPExcel->getActiveSheet(); $array = arra ...
- 使用NPOI快速导出导入Excel
这两天做项目需要导入导出EXCEL,是基于NPOI的封装,设计思路是使用DataTable,然后导出一个和DataTable一模一样的Excel表出来 github地址:https://github. ...
随机推荐
- Codeforces Round #321 (Div. 2) B. Kefa and Company 二分
B. Kefa and Company Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/580/pr ...
- linux就是这个范儿之融于心而表于行(1)
原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 .作者信息和本声明.否则将追究法律责 时间总是过得那么快,如流水一般哗啦啦的就淌走了一大堆!周遭事事沧桑变迁喧哗或耳语中流传的故事已渐模糊 ...
- powershell 查看程序的tcp网络连接
在运维工作中,常常查看某个业务的网络连接状况,在这里借用netstat来实现查找连接.用hash特性避免反复. $add=@{} while(1){ ps|?{$_.path -match 'E:\\ ...
- paip.提升性能---- 网站并发数的总结.txt
paip.提升性能---- 网站并发数的总结.txt 作者Attilax , EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.n ...
- eclipse启动不了报错java was started but returned exit code=13
http://zhidao.baidu.com/question/1367307106041927459.html http://zhidao.baidu.com/question/570567914 ...
- Migration from Zend Framework v2 to v3
Migration from Zend Framework v2 to v3 Zend Framework v2 to v3 has been intended as an incremental u ...
- javascript中window.event事件用法详解
转自http://www.jb51.net/article/32564.htm描述 event代表事件的状态,例如触发event对象的元素.鼠标的位置及状态.按下的键等等. event对象只在事件发生 ...
- Android自定义标题TitleView
Android开发过程中,经常遇到一个项目需要重复的定义相同样式的标题栏,Android相继推出了actionBar, toolBar, 相信有用到的朋友也会遇到一些不如意的时候,比如标题栏居中时,需 ...
- mvn打包
mvn install -DskipTests mvn install -Dmaven.test.skip=true
- 计算openlayers两点之间的距离
distanceTo: function(point) { var distance = 0.0; if ((this.x != null) && (this.y != null) & ...