C#导出DataGridView到Excel
public class ExcelHelper
{
private static object missing = Type.Missing; #region ================导出=================
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dgv"></param>
public static void ExportToExcel(System.Windows.Forms.DataGridView dgv)
{
ExportToExcel(dgv, , dgv.Columns.Count);
}
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="startColumnIndex">从第几列开始</param>
public static void ExportToExcel(System.Windows.Forms.DataGridView dgv, int startColumnIndex)
{
ExportToExcel(dgv, startColumnIndex, dgv.Columns.Count);
}
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="startColumnIndex">从第几列开始</param>
/// <param name="endColumnIndex">到第几列结束</param>
public static void ExportToExcel(System.Windows.Forms.DataGridView dgv, int startColumnIndex, int endColumnIndex)
{
if (dgv.Rows.Count == )
return;
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
app.UserControl = false;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(missing);
Microsoft.Office.Interop.Excel.Worksheet ws = app.ActiveWorkbook.Sheets[] as Microsoft.Office.Interop.Excel.Worksheet;
try
{
ExportToExcel(app, wb, ws, dgv, startColumnIndex, endColumnIndex);
}
finally
{
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect();
}
}
catch
{
System.Windows.Forms.MessageBox.Show("无法正常启动计算机上的EXCEL软件!", "系统提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
} /// <summary>
/// 导出到excel
/// </summary>
/// <param name="app"></param>
/// <param name="wb"></param>
/// <param name="ws"></param>
/// <param name="dgv"></param>
/// <param name="startColumnIndex">从第几列开始</param>
/// <param name="startColumnIndex">到第几列结束</param>
private static void ExportToExcel(Microsoft.Office.Interop.Excel.Application app, Microsoft.Office.Interop.Excel._Workbook wb, Microsoft.Office.Interop.Excel.Worksheet ws, System.Windows.Forms.DataGridView dgv, int startColumnIndex, int endColumnIndex)
{
Microsoft.Office.Interop.Excel.Range range;
int rowCount = dgv.Rows.Count;
int colCount = ;
int colIndex = ;
int rowIndex = ;
#region 开始到结束 int startIndex = ;//开始的列索引
int endIndex = dgv.Columns.Count;//结束的列索引
if (endColumnIndex < endIndex)
endIndex = endColumnIndex;
if (startIndex < endIndex && startColumnIndex < endIndex)
{
startIndex = startColumnIndex;
}
#endregion
for (int i = startIndex; i < endIndex; i++)
{
if (!dgv.Columns[i].Visible)
continue;
colCount++;
}
//foreach (DataGridViewColumn col in dgv.Columns)
//{
// if (!col.Visible)
// continue;
// colCount++;
//}
#region "Set title"
String endCellAddress = "";
if (colCount > && colCount <= )
{
endCellAddress = ((char)('A' + colCount)).ToString() + "";
}
else if (colCount > && colCount < * )
{
int iTemp = (int)Math.Ceiling((double)colCount / (double));
endCellAddress = ((char)('A' + iTemp)).ToString() + ((char)('A' + (colCount - * ))).ToString() + "";
}
else
{
throw new Exception("列数太多,操作出错!");
}
ws.Cells[, ] = "导出数据";
range = ws.get_Range("A1", endCellAddress);
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.Font.Size = ;
range.Font.Name = "黑体";
range.Borders.LineStyle = ;
range.Select();
range.Merge(false);
//range.Merge(ws.get_Range("A1", endCellAddress));
#endregion "Set title" #region " Set Header Values "
object[,] colValues = new object[, colCount + ];
colIndex = ;
colValues[, colIndex] = "序号";
for (int i = startIndex; i < endIndex; i++)
{
if (!dgv.Columns[i].Visible)
continue;
colValues[, colIndex + ] = dgv.Columns[i].HeaderText;
colIndex++;
}
//foreach (DataGridViewColumn col in dgv.Columns)
//{
// if (!col.Visible)
// continue;
// colValues[0, colIndex + 1] = col.HeaderText;
// colIndex++;
//} range = ws.get_Range(GetExcelCellName(, ), GetExcelCellName(colCount + , ));
range.Value2 = colValues;
#endregion #region " Header Style "
range.Font.Bold = true;
range.Font.Name = "Georgia";
range.Font.Size = ;
range.RowHeight = ;
range.EntireColumn.AutoFit();
#endregion #region " Set Row Values "
object[,] rowValues = new object[rowCount, colCount + ];
rowIndex = ;
foreach (System.Windows.Forms.DataGridViewRow row in dgv.Rows)
{
colIndex = ;
rowValues[rowIndex, colIndex] = rowIndex + ;
foreach (System.Windows.Forms.DataGridViewCell cell in row.Cells)
{
if (cell.ColumnIndex == )
{
colIndex++;
continue;
}
if (row.Cells[colIndex].Value.ToString().IsInt())
rowValues[row.Index, colIndex] = string.Format("'{0}", row.Cells[colIndex].Value.ToString());
else
rowValues[row.Index, colIndex] = row.Cells[colIndex].Value.ToString();
colIndex++;
}
rowIndex++;
} range = ws.get_Range(GetExcelCellName(, ), GetExcelCellName(colCount + , rowCount + ));
range.Value2 = rowValues;
#endregion #region " Row Style "
range.Font.Name = "Georgia";
range.Font.Size = ;
range.RowHeight = ;
range.EntireColumn.AutoFit();
range.Borders.ColorIndex = ;
#endregion #region " Set Borders "
range = ws.get_Range(GetExcelCellName(, ), GetExcelCellName(colCount + , rowCount + ));
range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
range.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
range.Borders.Color = System.Drawing.Color.Black.ToArgb();
#endregion
} #region " GetCellName " private static string GetExcelCellName(int fColIndex, int fRowIndex)
{
if (fColIndex <= || fColIndex > )
{
throw new Exception("Excel 列索引数值超出范围(1-256)!");
}
else if (fColIndex <= )
{
return GetExcelCellName(fColIndex) + fRowIndex.ToString();
}
else
{
string retLetter = GetExcelCellName(fColIndex / );
retLetter += GetExcelCellName(fColIndex % );
retLetter += fRowIndex.ToString();
return retLetter;
}
} private static string GetExcelCellName(int fColIndex)
{
int i = ;
foreach (string letter in Enum.GetNames(typeof(ExcelColumnLetters)))
{
if (i == fColIndex)
return letter;
i++;
}
throw new Exception("Excel 列索引数值超出范围(1-256)!");
} #endregion public enum ExcelColumnLetters
{
A = ,
B = ,
C = ,
D = ,
E = ,
F = ,
G = ,
H = ,
I = ,
J = ,
K = ,
L = ,
M = ,
N = ,
O = ,
P = ,
Q = ,
R = ,
S = ,
T = ,
U = ,
V = ,
W = ,
X = ,
Y = ,
Z =
}
#endregion }
C#导出DataGridView到Excel的更多相关文章
- winfrom导出DataGridView为Excel方法
声明:此方法需要电脑安装Excel软件 需要类库:Microsoft.Office.Interop.Excel.dll 可百度自行下载 方法代码: /// <summary> /// 导出 ...
- winform 导出datagridview 到excel
数据不多可以用下面的方式方法,如果数据较大,不建议这样使用,可能会比较卡如果电脑上没有Microsoft.Office.Interop.Excel.dll去找DLL下载站下载即可 需要先导入这个dll ...
- C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel
其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...
- 【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据
准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...
- C# 导出dataGridView中的值到Excel
C# 怎么导出dataGridView中的值到Excel 1 2 3 4 5 6 在系统应用过程中,数据是系统的核心.如果直接在应用软件中看数据,有时也有些不便,所以就会把系统数据转换成Excel格式 ...
- 一个方便且通用的导出数据到 Excel 的类库
一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...
- 1.ASP.NET MVC使用EPPlus,导出数据到Excel中
好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件. 源代码下载:https://github.com/caofangshe ...
- 导出数据到Excel --使用ExcelReport有感
先看图,这是几个月前用NPOI写的导出数据到Excel,用了上百行代码,而且难控制,导出来也比较难看 excel打开的效果 下面是我用ExcelReport类库导出到Excel的操作 1.首先引用Ex ...
- 使用Open xml 操作Excel系列之二--从data table导出数据到Excel
由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...
随机推荐
- c#实现word,winWordControl 文档不允许复制、粘贴、隐藏工具栏、快捷保存
1.隐藏工具栏 //隐藏工具栏 ; i <= winWordControl1.document.CommandBars.Count; i++) { winWordControl1.documen ...
- CloudStack采用spring加载bean(cloud-framework-spring-module模块)
CloudStackContextLoaderListener /* * Licensed to the Apache Software Foundation (ASF) under one * or ...
- IE6/IE7/IE8 FF常见问题解决
(从已经死了一次又一次终于挂掉的百度空间人工抢救出来的,发表日期2014-04-08) <style type="text/css" > *{ margin:0px a ...
- Python常用网页字符串处理技巧
首先一些Python字符串处理的简易常用的用法.其他的以后用到再补充. 1.去掉重复空格 s = "hello hello hello" s = ' '.join(s.split( ...
- Hadoop ecosystem
How did it all start- huge data on the web! Nutch built to crawl this web data Huge data had to save ...
- Flex中实现类似Javascript的confirm box
Javascript是阻塞的,你可以使用confirm()来获取用户的选择,并根据用户的选择结果继续下面的操作. Flex是非阻塞的,在执行过程中没有类似JS中confirm()那种等待用户选择后继续 ...
- PostgreSQL的注释嵌套的例子
pgsql=# -- Multiline comments pgsql=# SELECT 'Multi' /* This comment extends across pgsql*# * number ...
- Codeforces Beta Round #12 (Div 2 Only) D. Ball sort/map
D. Ball Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/problemset/problem/12/D D ...
- iOS开发——UI篇Swift篇&UISegmentedControl
UISegmentedControl override func viewDidLoad() { super.viewDidLoad() titleLabel.text = titleString / ...
- 来自 Github 的图形化 Git 使用教程
转载:http://www.linuxeden.com/html/news/20120628/126451.html 这是来自 Github 上对 Git 常用操作进行简短介绍以及可视化图形操作说明的 ...