C#数据导出Excel详细介绍
概要:
excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用。
Excel知识点。
一、添加引用和命名空间
添加Microsoft.Office.Interop.Excel引用,它的默认路径是C:\Program Files\Microsoft Visual
Studio 9.0\Visual Studio Tools for
Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll
代码中添加引用using
Microsoft.Office.Interop.Excel;
二、Excel类的简单介绍
此命名空间下关于Excel类的结构分别为:
ApplicationClass – 就是我们的excel应用程序。
Workbook –
就是我们平常见的一个个excel文件,经常是使用Workbooks类对其进行操作。
Worksheet – 就是excel文件中的一个个sheet页。
Worksheet.Cells[row, column] –
就是某行某列的单元格,注意这里的下标row和column都是从1开始的,跟我平常用的数组或集合的下标有所不同。
知道了上述基本知识后,利用此类来操作excel就清晰了很多。
三、Excel的操作
任何操作Excel的动作首先肯定是用excel应用程序,首先要new一个ApplicationClass 实例,并在最后将此实例释放。
ApplicationClass xlsApp = new ApplicationClass(); // 1. 创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。
if (xlsApp == null)
{
//对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel
}
1. 打开现有的Excel文件
Workbook workbook = xlsApp.Workbooks.Open(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet mySheet = workbook.Sheets[] as Worksheet; //第一个sheet页
mySheet.Name = "testsheet"; //这里修改sheet名称
2.复制sheet页
mySheet.Copy(Type.Missing, workbook.Sheets[]); //复制mySheet成一个新的sheet页,复制完后的名称是mySheet页名称后加一个(2),这里就是testsheet(2),复制完后,Worksheet的数量增加一个
注意
这里Copy方法的两个参数,指是的复制出来新的sheet页是在指定sheet页的前面还是后面,上面的例子就是指复制的sheet页在第一个sheet页的后面。
3.删除sheet页
xlsApp.DisplayAlerts = false; //如果想删除某个sheet页,首先要将此项设为fasle。
(xlsApp.ActiveWorkbook.Sheets[] as Worksheet).Delete();
4.选中sheet页
(xlsApp.ActiveWorkbook.Sheets[] as Worksheet).Select(Type.Missing); //选中某个sheet页
5.另存excel文件
workbook.Saved = true;
workbook.SaveCopyAs(filepath);
6.释放excel资源
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlsApp.Quit();
xlsApp = null;
一般的我们传入一个DataTable生成Excel代码
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
protected void ExportExcel(DataTable dt)
{
if (dt == null||dt.Rows.Count==) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ;
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ];
range.Interior.ColorIndex = ;
range.Font.Bold = true;
}
for (int r = ; r < dt.Rows.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + , i + ] = dt.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)( * rowRead)) / totalCount;
}
xlApp.Visible = true;
}
如果要在excel中插入图片,我们需要把代码加入一行即可,如下所示
protected void ExportExcel(DataTable dt)
{
if (dt == null || dt.Rows.Count == ) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ;
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ];
range.Interior.ColorIndex = ;
}
for (int r = ; r < dt.Rows.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
try
{
worksheet.Cells[r + , i + ] = dt.Rows[r][i].ToString();
}
catch
{
worksheet.Cells[r + , i + ] = dt.Rows[r][i].ToString().Replace("=", "");
}
}
rowRead++;
percent = ((float)( * rowRead)) / totalCount;
} worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, , , , );
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "", "Red", , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, , );
xlApp.Visible = true;
}
我们调用如下:
public void GenerateExcel()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(string));
DataRow dr = dt.NewRow();
dr["Name"] = "spring";
dr["Age"] = "";
dt.Rows.Add(dr);
dt.AcceptChanges();
ExportExcel(dt);
}
运行结果如下所示:
其中如下代码的作用是
worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, , , , );
在Excel的指定位置加入图片
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "", "Red", , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, , );
在Excel的指定位置加入文本框,和里面的内容.
我们可以这样来设计一个ExcelBase的基类:
先创建一个ExcelBE.cs:
public class ExcelBE
{
private int _row = ;
private int _col = ;
private string _text = string.Empty;
private string _startCell = string.Empty;
private string _endCell = string.Empty;
private string _interiorColor = string.Empty;
private bool _isMerge = false;
private int _size = ;
private string _fontColor = string.Empty;
private string _format = string.Empty; public ExcelBE(int row, int col, string text, string startCell, string endCell, string interiorColor, bool isMerge, int size, string fontColor, string format)
{
_row = row;
_col = col;
_text = text;
_startCell = startCell;
_endCell = endCell;
_interiorColor = interiorColor;
_isMerge = isMerge;
_size = size;
_fontColor = fontColor;
_format = format;
} public ExcelBE()
{ } public int Row
{
get { return _row; }
set { _row = value; }
} public int Col
{
get { return _col; }
set { _col = value; }
} public string Text
{
get { return _text; }
set { _text = value; }
} public string StartCell
{
get { return _startCell; }
set { _startCell = value; }
} public string EndCell
{
get { return _endCell; }
set { _endCell = value; }
} public string InteriorColor
{
get { return _interiorColor; }
set { _interiorColor = value; }
} public bool IsMerge
{
get { return _isMerge; }
set { _isMerge = value; }
} public int Size
{
get { return _size; }
set { _size = value; }
} public string FontColor
{
get { return _fontColor; }
set { _fontColor = value; }
} public string Formart
{
get { return _format; }
set { _format = value; }
} }
接下来创建ExcelBase.cs:
public class ExcelBase
{
private Microsoft.Office.Interop.Excel.Application app = null;
private Microsoft.Office.Interop.Excel.Workbook workbook = null;
private Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
private Microsoft.Office.Interop.Excel.Range workSheet_range = null; public ExcelBase()
{
createDoc();
} public void createDoc()
{
try
{
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
workbook = app.Workbooks.Add();
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[];
}
catch (Exception e)
{
Console.Write("Error");
}
finally
{
}
} public void InsertData(ExcelBE be)
{
worksheet.Cells[be.Row, be.Col] = be.Text;
workSheet_range = worksheet.get_Range(be.StartCell, be.EndCell);
workSheet_range.MergeCells = be.IsMerge;
workSheet_range.Interior.Color = GetColorValue(be.InteriorColor);
workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
workSheet_range.ColumnWidth = be.Size;
workSheet_range.Font.Color = string.IsNullOrEmpty(be.FontColor) ? System.Drawing.Color.White.ToArgb() : System.Drawing.Color.Black.ToArgb();
workSheet_range.NumberFormat = be.Formart;
} private int GetColorValue(string interiorColor)
{
switch (interiorColor)
{
case "YELLOW":
return System.Drawing.Color.Yellow.ToArgb();
case "GRAY":
return System.Drawing.Color.Gray.ToArgb();
case "GAINSBORO":
return System.Drawing.Color.Gainsboro.ToArgb();
case "Turquoise":
return System.Drawing.Color.Turquoise.ToArgb();
case "PeachPuff":
return System.Drawing.Color.PeachPuff.ToArgb(); default:
return System.Drawing.Color.White.ToArgb();
}
}
}
调用的代码如下:
private void btnRun_Click(object sender, EventArgs e)
{
ExcelBase excel = new ExcelBase();
//creates the main header
ExcelBE be = null;
be = new ExcelBE (, , "Total of Products", "B5", "D5", "YELLOW", true, , "n",null);
excel.InsertData(be);
//creates subheaders
be = new ExcelBE (, , "Sold Product", "B6", "B6", "GRAY", true, , "",null);
excel.InsertData(be);
be=new ExcelBE(, , "", "C6", "C6", "GRAY", true, , "",null);
excel.InsertData(be);
be=new ExcelBE (, , "Initial Total", "D6", "D6", "GRAY", true, , "",null);
excel.InsertData(be);
//add Data to cells
be=new ExcelBE (, , "", "B7", "B7",null,false,,"", "#,##0");
excel.InsertData(be);
be=new ExcelBE (, , "", "C7", "C7", null,false,,"",null);
excel.InsertData(be);
be = new ExcelBE(, , "", "D7", "D7
C#数据导出Excel详细介绍的更多相关文章
- asp.net C#数据导出Excel实例介绍
excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用. Excel知识点. 一.添加引用和命名空间 添加Microsoft.Office.Interop.Excel引用,它 ...
- 【asp.net】将GridView数据导出Excel
概要: 中午睡了一会,醒来的时候看到老师叫我去办公室,需求是这样的,把excel表中的每个同学,判断图片目录中是否有对应的照片(图片的名字用的学号或身份证号码) 没有对应图片的学生记录,存入自己的数据 ...
- Java使用POI实现数据导出excel报表
Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...
- 百度地图里面搜索到的公司商家电话导出表格?怎样将把百度地图里面搜索到的公司 电话 地址 等数据导出excel里?
好多人在问:如何将百度地图里面搜索到的公司商家电话导出表格?怎样将把百度地图里面搜索到的公司 电话 地址 等数据导出excel里? 现在,很多人都在网络上找商家,联系业务. 百度地图里有很多的商家联系 ...
- JavaScript 上万条数据 导出Excel文件(改装版)
最近项目要js实现将数据导出excel文件,网上很多插件实现~~那个开心呀,谁知道后面数据量达到上万条时出问题:浏览器不仅卡死,导出的excel文件一直提示网络失败.... debug调试发现var ...
- JavaScript 上万条数据 导出Excel文件 页面卡死
最近项目要js实现将数据导出excel文件,网上很多插件实现~~那个开心呀,谁知道后面数据量达到上万条时出问题:浏览器不仅卡死,导出的excel文件一直提示网络失败.... debug调试发现var ...
- 将页面中表格数据导出excel格式的文件(vue)
近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...
- ASP.NET导出数据到Excel 实例介绍
ASP.NET导出数据到Excel 该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 新建 ...
- .net解决数据导出excel时的格式问题
在项目中一般都需要将报表数据导出到EXCEL中,但经常出现导出长串数据(如身份证)到EXCEL中后显示为科学计数法的格式,或者报表中显示为001的数据导出到Excel后成了1的格式. 下面简单介绍一下 ...
随机推荐
- RPC与REST的差别
一:RPC RPC 即远程过程调用, 非常easy的概念, 像调用本地服务(方法)一样调用server的服务(方法). 通常的实现有 XML-RPC , JSON-RPC , 通信方式基本同样, 所不 ...
- 【9102】&&【a102】求a/b的高精度值
Time Limit: 10 second Memory Limit: 2 MB 问题描述 计算a/b的精度值,设a,b以一般整数输入,计算结果精确到小数后20位(结果四舍五入). Input 文件输 ...
- 一题多解(五) —— topK(数组中第 k 大/小的数)
根据对称性,第 k 大和第 k 小,在实现上,是一致的,我们就以第 k 小为例,进行说明: 法 1 直接排序(sort(A, A+N)),当使用一般时间复杂度的排序算法时,其时间复杂度为 O(N2) ...
- maven Java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
如果你可以确认你的maven Dependencies中已经导入了如下的jar包,那么你就要检查下Deployment Assembly 选中项目 alt+enter,然后查看maven依赖有没有被添 ...
- PAT 1041-1050 题解
浏览全部代码:请戳 本文谨代表个人思路,欢迎讨论;) 1041. Be Unique (20) 题意 给出 N (<=105)个数(数值范围为 [1, 104]),找到其中不重复的第一个数字.比 ...
- pushbutton成为可点击的图标(实现全透明,不论点击与否都只显示Icon)(也就是一个万能控件)
需求 需要2个按钮,一个是音乐开关,一个是关闭窗口,此文章关闭pushButton的透明问题(hovered+pressed都不会有背景色和边框的变化) 原理 使窗口完全透明 代码 _pPushBut ...
- Stompjs websocket vue
公司项目要求要有消息提醒机制 , 多方面考虑用了ActiveMQ ,基本上现在主流的后台语言都没啥问题 , php phthon java nodejs , 等等都没问题 , 各位道友可以去查阅相关资 ...
- Android中WebView的相关使用
近期做的项目中,遇到个非常棘手的问题: 客户给我的数据是有限制的,因此,在返回某条详细页面内容的时候,他仅仅能给我一个html片段,里面包括 文字,图片以及附件的下载地址.假设网页模版规范的爱比較好说 ...
- DDD实战8_2 利用Unity依赖注入,实现接口对应实现类的可配置
1.在Util类库下新建DIService类 /// <summary> /// 创建一个类,对应在配置文件中配置的DIServices里面的对象的 key /// </summar ...
- HDU2665 Kth number 【合并树】
Kth number Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...