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中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...
随机推荐
- call()和apply()方法
还在处在刚刚学习JavaScript的初级阶段,所以理解相对浅显,是一种简单的模式理解.这里做一个笔记,让自己在回顾的时候,更加牢记. call()和apply()的形式 A.call(B," ...
- Object Pascal对象模型中构造函数之研究
http://www.delphi2007.net/delphiblog/html/delphi_2004511950333715.html 前言 近期,一直在使用 C++ 与 Object Pasc ...
- PostgreSQL中使用枚举类型
https://wiki.postgresql.org/wiki/Enum 建立enum: pgsql=# CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy' ...
- C++学习笔记之迭代器
模板是的算法独立于存储的数据类型,而迭代器使算法独立于使用的容器类型.理解迭代器是理解STL的关键. 迭代器应该具备的特征: (1)应该能够对迭代器进行解除引用的操作,以便能够访问它引用的值.即如果P ...
- C++经典面试题
1.int a=5,则 ++(a++)的值是() A.5 B. 6 C.7 D.逻辑错误 a++返回的是一个暂时变量,这里是右值,不能再前面++了 2.以下 ...
- hdu 5286 How far away ? tarjan/lca
How far away ? Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pi ...
- This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分 解决方案
但web启用了md5加密后 有可能出现这样的错误 This implementation is not part of the Windows Platform FIPS validated cryp ...
- Out of resources when opening file 错误解决
mysqldump: Got error: 23: Out of resources when opening file ‘./mydb/tax_calculation_rate_title.MYD’ ...
- Java对证书的操作
1 Java程序从证书文件读取证书 import java.io.*; import java.security.cert.*; public class PrintCert{ public stat ...
- libgo协程库:网络性能完爆ASIO异步模型(-O3测试)
在purecpp社区的github组织中有一个协程库:https://github.com/yyzybb537/libgo 近日有用户找到我,想要了解一下libgo库在网络方面的性能,于是选取已入选标 ...