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中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...
随机推荐
- URAL 1233 - Amusing Numbers
首先计算出k至少为第几位,如果m小于这个数,那么输出0 还有一种情况, 就是10的i次方的这种情况,如果i+1等于m,那么直接输出k,否则输出0 其他的情况,就是二分,然后判断计算其插入到k之前的数的 ...
- 用java写一个web服务器
一.超文本传输协议 Web服务器和浏览器通过HTTP协议在Internet上发送和接收消息.HTTP协议是一种请求-应答式的协议——客户端发送一个请求,服务器返回该请求的应答.HTTP协议使用可靠的T ...
- linux-用户建立及权限分配
1.建立用户 useradd –d /usr/test -m test 此命令创建了一个用户test,用户主目录为/usr/test 2.设置用户密码 .修改自己的密码 passwd ,需要输入旧 ...
- PageValidate 类
转载:http://www.cnblogs.com/sufei/archive/2010/01/14/1648028.html using System.Text.RegularExpressions ...
- 负载均衡LVS集群详解
一.LB--负载均衡 在负载均衡集群中需要一个分发器,我们将其称之为Director,它位于多台服务器的上面的中间层,根据内部锁定义的规则或调度方式从下面的服务器群中选择一个以此来进行响应请求,而其 ...
- uva140 - Bandwidth
Bandwidth Given a graph (V,E) where V is a set of nodes and E is a set of arcs in VxV, and an orderi ...
- hdu 5258 数长方形 离散化
数长方形 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5258 Des ...
- 【转】Delphi多线程学习(9):多线程数据库查询(ADO)
原文:http://www.cnblogs.com/djcsch2001/articles/2382559.html ADO多线程数据库查询通常会出现3个问题: 1.CoInitialize 没有调用 ...
- 如何在XAF中显示自定义窗体和控件
https://www.devexpress.com/Support/Center/Example/Details/E911
- curl命令具体解释
对于windows用户假设用Cygwin模拟unix环境的话,里面没有带curl命令,要自己装,所以建议用Gow来模拟,它已经自带了curl工具,安装后直接在cmd环境中用curl命令就可,由于路径已 ...