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. 一种基于PTP 协议的局域网高精度时钟同步方法(转)

    原文地址 http://www.dzsc.com/data/html/2011-1-17/88338.html 1 引言 在分布式系统中, 常常需要一个全局时间, 用来确定系统中各种事件发生的先后.协 ...

  2. APK扩展文件及使用

    转自:http://blog.csdn.net/myarrow/article/details/7760579 一.APK扩展文件基本知识 Android Market (Google Play St ...

  3. STUN: NAT 类型检测方法

    STUN(Simple Transversal of UDP through NATs)[21]是RFC3489 规定的一种NAT 穿透方式,它采用辅助的方法探测NAT 的IP 和端口. STUN 的 ...

  4. 组合方法(ensemble method) 与adaboost提升方法

    组合方法: 我们分类中用到非常多经典分类算法如:SVM.logistic 等,我们非常自然的想到一个方法.我们是否可以整合多个算法优势到解决某一个特定分类问题中去,答案是肯定的! 通过聚合多个分类器的 ...

  5. Codeforces Gym 100015H Hidden Code 暴力

    Hidden Code 题目连接: http://codeforces.com/gym/100015/attachments Description It's time to put your hac ...

  6. EF TO MYSQL 无法查询中文的解决方法

    ef dbfirst 连接mysql 5.7版本 起初,连edmx都无法生成 报错 Entity : The value for column 'IsPrimaryKey' in table 'Tab ...

  7. 创建C#串口通信程序详解

    在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports.这个新的框架不但可以访问计算机上的串口,还可以和串口设备进行通信.我们将使用标准 ...

  8. java建立二叉树,递归/非递归先序遍历,递归/非递归中序遍历,层次遍历

    import java.util.LinkedList; import java.util.Scanner; import java.util.Stack; //structure of binary ...

  9. (hdu step 8.1.1)ACboy needs your help again!(STL中栈和队列的基本使用)

    题目: ACboy needs your help again! Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ...

  10. [C++基础]随机数,随机种子数

    #include <stdlib.h> #include <iostream> #include <ctime> using namespace std; void ...