C# datatable 导出到Excel
datatable导出到Excel
/// <summary>
/// 将DataTable导出为Excel文件(.xls)
/// </summary>
/// <param name="dt">要导出的DataTable</param>
public static void ErrorCrd_ExportToExcel(DataTable dt)
{
if (dt == null) return; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
Msg.Warning("无法创建Excel对象,可能您的电脑未安装Excel");
return;
}
System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
saveDia.Filter = "Excel|*.xls";
saveDia.Title = "导出为Excel文件";
if (saveDia.ShowDialog() == System.Windows.Forms.DialogResult.OK
&& !string.Empty.Equals(saveDia.FileName))
{
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[];//取得sheet1
Microsoft.Office.Interop.Excel.Range range = null;
long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ;
string fileName = saveDia.FileName;
//写入标题
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 = 15;//背景颜色
range.Font.Bold = true;//粗体
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
//加边框
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
//range.ColumnWidth = 4.63;//设置列宽
//range.EntireColumn.AutoFit();//自动调整列宽
//r1.EntireRow.AutoFit();//自动调整行高
}
//写入内容
for (int r = ; r < dt.DefaultView.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + , i + ] = dt.DefaultView[r][i];
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + , i + ];
range.Font.Size = ;//字体大小
//加边框
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.EntireColumn.AutoFit();//自动调整列宽
}
rowRead++;
percent = ((float)( * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
if (dt.Columns.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
}
try
{
workbook.Saved = true;
workbook.SaveCopyAs(fileName);
}
catch (Exception ex)
{
Msg.ShowError("导出文件时出错,文件可能正被打开!\n" + ex.Message);
return;
} workbooks.Close();
if (xlApp != null)
{
xlApp.Workbooks.Close();
xlApp.Quit();
int generation = System.GC.GetGeneration(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
System.GC.Collect(generation);
}
GC.Collect();//强行销毁
#region 强行杀死最近打开的Excel进程
System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
System.DateTime startTime = new DateTime();
int m, killId = ;
for (m = ; m < excelProc.Length; m++)
{
if (startTime < excelProc[m].StartTime)
{
startTime = excelProc[m].StartTime;
killId = m;
}
}
if (excelProc[killId].HasExited == false)
{
excelProc[killId].Kill();
}
#endregion
Msg.ShowInformation("导出成功!");
}
}
Excel 数据导出(引)
using System;
using System.Data;
using System.Data.OleDb; namespace ZFSoft.Joint
{
public class ExcelIO
{
private int _ReturnStatus;
private string _ReturnMessage; /// <summary>
/// 执行返回状态
/// </summary>
public int ReturnStatus
{
get
{
return _ReturnStatus;
}
} /// <summary>
/// 执行返回信息
/// </summary>
public string ReturnMessage
{
get
{
return _ReturnMessage;
}
} public ExcelIO()
{
} /// <summary>
/// 导入EXCEL到DataSet
/// </summary>
/// <param name="fileName">Excel全路径文件名</param>
/// <returns>导入成功的DataSet</returns>
public DataTable ImportExcel(string fileName)
{
//判断是否安装EXCEL
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
_ReturnStatus = -;
_ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
return null;
} //判断文件是否被其他进程使用
Microsoft.Office.Interop.Excel.Workbook workbook;
try
{
workbook = xlApp.Workbooks.Open(fileName, , false, , "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, , true, , );
}
catch
{
_ReturnStatus = -;
_ReturnMessage = "Excel文件处于打开状态,请保存关闭";
return null;
} //获得所有Sheet名称
int n = workbook.Worksheets.Count;
string[] SheetSet = new string[n];
System.Collections.ArrayList al = new System.Collections.ArrayList();
for (int i = ; i <= n; i++)
{
SheetSet[i - ] = ((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[i]).Name;
} //释放Excel相关对象
workbook.Close(null, null, null);
xlApp.Quit();
if (workbook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
GC.Collect(); //把EXCEL导入到DataSet
DataSet ds = new DataSet();
DataTable table = new DataTable();
string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + fileName + ";Extended Properties=Excel 8.0";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter da;
string sql = "select * from [" + SheetSet[] + "$] ";
da = new OleDbDataAdapter(sql, conn);
da.Fill(ds, SheetSet[]);
da.Dispose();
table = ds.Tables[];
conn.Close();
conn.Dispose();
}
return table;
} /// <summary>
/// 把DataTable导出到EXCEL
/// </summary>
/// <param name="reportName">报表名称</param>
/// <param name="dt">数据源表</param>
/// <param name="saveFileName">Excel全路径文件名</param>
/// <returns>导出是否成功</returns>
public bool ExportExcel(string reportName, System.Data.DataTable dt, string saveFileName)
{
if (dt == null)
{
_ReturnStatus = -;
_ReturnMessage = "数据集为空!";
return false;
} bool fileSaved = false;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
_ReturnStatus = -;
_ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
return false;
} 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[];//取得sheet1
worksheet.Cells.Font.Size = ;
Microsoft.Office.Interop.Excel.Range range; long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ; worksheet.Cells[, ] = reportName;
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, ]).Font.Size = ;
((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, ]).Font.Bold = true; //写入字段
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;
} range = worksheet.get_Range(worksheet.Cells[, ], worksheet.Cells[dt.Rows.Count + , dt.Columns.Count]);
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
if (dt.Rows.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
}
if (dt.Columns.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
} //保存文件
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
_ReturnStatus = -;
_ReturnMessage = "导出文件时出错,文件可能正被打开!\n" + ex.Message;
}
}
else
{
fileSaved = false;
} //释放Excel对应的对象
if (range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if (worksheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
}
if (workbook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
}
if (workbooks != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
workbooks = null;
}
xlApp.Application.Workbooks.Close();
xlApp.Quit();
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
GC.Collect();
return fileSaved;
}
}
}
C# datatable 导出到Excel的更多相关文章
- DataTable导出到Excel
简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...
- [转].net 使用NPOI或MyXls把DataTable导出到Excel
本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...
- DataTable 导出到 Excel 类
底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...
- c# DataTable导出为excel
/// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt& ...
- DataTable导出到Excel(.NET 4.0)
最近在论坛里又看到很多关于DataTable(DataSet)导入Excel的帖子,我也温故知新一下,用VS2010重新整理了一个Sample.这个问题简化一下就是内存数据到文件,也就是遍历赋值,只不 ...
- NPOI使用Datatable导出到Excel
首先要引用dll 下载地址:http://pan.baidu.com/s/1dFr2m 引入命名空间: using NPOI.HSSF.UserModel;using NPOI.SS.UserMode ...
- C# 将datatable导出成Excel
public void Result( ){try{StringBuilder sql = new StringBuilder();List<SqlParameter> parameter ...
- csv/json/list/datatable导出为excel的通用模块设计
导出excel的场景我一般都是一个List直接导出成一张sheet,用Npoi.Mapper库很方便,最近我经常是需要将接口返回的jsonarray转成一张excel表,比如从elasticsearc ...
- 将DataTable导出到Excel
/// <summary> /// 导出Excel /// </summary> /// <param name="dtData"></p ...
随机推荐
- moc_XXXX.o:(.data.rel.ro._ZTI12CalculatorUI[_ZTI12CalculatorUI]+0x10): undefined reference to `typeinfo for QWidget' collect2: error: ld returned 1 exit status make: *** [Makefile:144: myCalculator]
main.cpp:(.text.startup+0x22): undefined reference to `QApplication::QApplication(int&, char**, ...
- JMeter 性能测试实例
一.性能测试分类: 1.基准测试 2.并发测试 3.负载测试 4.压力测试 1.基准测试: 也是单用户测试,测试环境确定以后,对业务模型中的重要业务做单独的测试,获取单用户运行时的各项性能指标,为多用 ...
- python基本数据类型常用方法
python基本数据类型 1.整型 1.1 int 1.2 bit_lenght # 当前数字的二进制位数,至少用n位表示 r = age.bit_length() >>> a = ...
- 前端之JQuery:JQuery文档操作
jquery之文档操作 一.相关知识点总结1.CSS .css() - .css("color") -> 获取color css值 - .css("color&qu ...
- idea 2018版最新激活注册方法
1. 下载破解补丁文件,路径为:http://idea.lanyus.com/jar/JetbrainsCrack-2.7-release-str.jar 2.将补丁放在安装包的/bin路径下,如图中 ...
- ubuntu16.04 开启FTP服务
配置ftp 1.安装 vsftpd服务器 sudo apt install vsftpd 2.创建一个ftp文件夹 (可以跳过) sudo mkdir /home/ftp 3.新建ftp用户,并指向它 ...
- nginx限制文件访问速率
需求: 一个文件下载功能需要限制文件同时访问的并发数和当个连接的访问速率: 配置: 在http context内增加: limit_conn_zone $binary_remote_addr zone ...
- 决策树剪枝算法-悲观剪枝算法(PEP)
前言 在机器学习经典算法中,决策树算法的重要性想必大家都是知道的.不管是ID3算法还是比如C4.5算法等等,都面临一个问题,就是通过直接生成的完全决策树对于训练样本来说是“过度拟合”的,说白了是太精确 ...
- iOS 推送角标解决方案
在App启动时:didFinishLaunchingWithOptions 方法中:application.applicationIconBadgeNumber = ; //角标清零 在读消息时: a ...
- Wannafly挑战赛16 #E 弹球弹弹弹 splay+基环树+各种思维
链接:https://ac.nowcoder.com/acm/problem/16033来源:牛客网 有n个位置,标号为1到n的整数,m次操作,第i次操作放置一个弹球在b[i] xor c[i-1]处 ...