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的更多相关文章

  1. winfrom导出DataGridView为Excel方法

    声明:此方法需要电脑安装Excel软件 需要类库:Microsoft.Office.Interop.Excel.dll 可百度自行下载 方法代码: /// <summary> /// 导出 ...

  2. winform 导出datagridview 到excel

    数据不多可以用下面的方式方法,如果数据较大,不建议这样使用,可能会比较卡如果电脑上没有Microsoft.Office.Interop.Excel.dll去找DLL下载站下载即可 需要先导入这个dll ...

  3. C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

    其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...

  4. 【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据

    准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...

  5. C# 导出dataGridView中的值到Excel

    C# 怎么导出dataGridView中的值到Excel 1 2 3 4 5 6 在系统应用过程中,数据是系统的核心.如果直接在应用软件中看数据,有时也有些不便,所以就会把系统数据转换成Excel格式 ...

  6. 一个方便且通用的导出数据到 Excel 的类库

    一个方便且通用的导出数据到 Excel 的类库 起源: 之前在做一个项目时,客户提出了许多的导出数据的需求: 导出用户信息 导出业务实体信息 各种查询都要能导出 导出的数据要和界面上看到的一致 可以分 ...

  7. 1.ASP.NET MVC使用EPPlus,导出数据到Excel中

    好久没写博客了,今天特地来更新一下,今天我们要学习的是如何导出数据到Excel文件中,这里我使用的是免费开源的Epplus组件. 源代码下载:https://github.com/caofangshe ...

  8. 导出数据到Excel --使用ExcelReport有感

    先看图,这是几个月前用NPOI写的导出数据到Excel,用了上百行代码,而且难控制,导出来也比较难看 excel打开的效果 下面是我用ExcelReport类库导出到Excel的操作 1.首先引用Ex ...

  9. 使用Open xml 操作Excel系列之二--从data table导出数据到Excel

    由于Excel中提供了透视表PivotTable,许多项目都使用它来作为数据分析报表. 在有些情况下,我们需要在Excel中设计好模板,包括数据源表,透视表等, 当数据导入到数据源表时,自动更新透视表 ...

随机推荐

  1. 在sphinx中应用复杂过滤条件

    一.问题的引入   在sphinx应用中,需要对数据进行复杂的条件过滤,刷选出我们需要的数据.这个过程,等同于mysql查询中的where条件.   但sphinx本身的filter并不能支持复杂的逻 ...

  2. 【转】知道创宇研发技能表v2.1

    转自:http://blog.knownsec.com/Knownsec_RD_Checklist/v2.1.html# 知道创宇研发技能表v2.1 创建时间:2012/12/1 2013/4/26 ...

  3. jQuery + jQuery Mobile 实现省市二级下拉列表页面

    一.需求: 提供省.市下拉列表,当用户选择省一级下拉列表项后,市下拉列表的各个选项自动变为该省对应的城市列表. 二.效果: 三.实现: 1.省市json数据,来自: http://www.cnblog ...

  4. 用JSP实现的商城购物车模块

    这两天,在学习JSP,正好找个小模块来练练手: 下面就是实现购物车模块的页面效果截图: 图1. 产品显示页面 通过此页面进行产品选择,增加到购物车 图2 .购物车页面 图3 . 商品数量设置 好了,先 ...

  5. Some tips on using HashSet<T> and List<T>

    This article is written based on my colleague's review Most of the times, when I want to use a colle ...

  6. [AngularJS] Using the Angular scope $destroy event and method

    With Angular scopes, you have access to a $destroy event that can be used to watch $scope events. Th ...

  7. 谈C#中的Delegate

    引言 Delegate是Dotnet1.0的时候已经存在的特性了,但由于在实际工作中一直没有机会使用Delegate这个特性,所以一直没有对它作整理.这两天,我再度翻阅了一些关于Delegate的资料 ...

  8. Hibernate Validation注解列表

    下面是主要的验证注解及说明: 注解 适用的数据类型 说明 @AssertFalse Boolean, boolean 验证注解的元素值是false @AssertTrue Boolean, boole ...

  9. Selenium1(RC)与Selenium2(WebDriver)的概念介绍

    最近网上学习了Selenium1和selenium2,自己做一些总结,方便以后查阅. 部分内容引用: http://www.cnblogs.com/hyddd/archive/2009/05/30/1 ...

  10. 16g u盘变 成1g u盘 解决方案,使用驱动器中的光盘之前需要将其格式化

    1\ 计算机----管理------磁盘管理  有一个黑色区域是未分配的 2\ 1)进入cmd 命令行窗口2)输入 diskpart,并回车.弹出系统提示,选是即可.3)输入 list disk,并回 ...