求教用NPOI读取excel时间到DataTable中时如何不让表头生成

2014年6月 .NET技术大版内专家分月排行榜第二2014年1月 .NET技术大版内专家分月排行榜第二
2014年2月 .NET技术大版内专家分月排行榜第三2013年4月 .NET技术大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。C#中如何使用NPOI库读写Excel文件 - C#教程 - 编程入门网
C#中如何使用NPOI库读写Excel文件
NPOI 是开源的 POI 项目的.NET版,可以用来读写Excel,Word,PPT文件。在处理Excel文件上,NPOI 可以同时兼容 xls 和 xlsx。官网提供了一份 Examples,给出了很多应用场景的例子,打包好的二进制文件类库,也仅有几MB,使用非常方便。
NPOI使用HSSFWorkbook类来处理xls,XSSFWorkbook类来处理xlsx,它们都继承接口IWorkbook,因此可以通过IWorkbook来统一处理xls和xlsx格式的文件。
以下是简单的例子
public void ReadFromExcelFile(string filePath)
IWorkbook wk =
string extension = System.IO.Path.GetExtension(filePath);
FileStream fs = File.OpenRead(filePath);
if (extension.Equals(&.xls&))
//把xls文件中的数据写入wk中
wk = new HSSFWorkbook(fs);
//把xlsx文件中的数据写入wk中
wk = new XSSFWorkbook(fs);
fs.Close();
//读取当前表数据
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(0);
//读取当前行数据
//LastRowNum 是当前表的总行数-1(注意)
int offset = 0;
for (int i = 0; i &= sheet.LastRowN i++)
row = sheet.GetRow(i);
//读取当前行数据
if (row != null)
//LastCellNum 是当前行的总列数
for (int j = 0; j & row.LastCellN j++)
//读取该行的第j列数据
string value = row.GetCell(j).ToString();
Console.Write(value.ToString() + & &);
Console.WriteLine(&\n&);
catch (Exception e)
//只在Debug模式下才输出
Console.WriteLine(e.Message);
Excel中的单元格是有不同数据格式的,例如数字,日期,字符串等,在读取的时候可以根据格式的不同设置对象的不同类型,方便后期的数据处理。
//获取cell的数据,并设置为对应的数据类型
public object GetCellValue(ICell cell)
object value =
if (cell.CellType != CellType.Blank)
switch (cell.CellType)
case CellType.Numeric:
// Date Type的数据CellType是Numeric
if (DateUtil.IsCellDateFormatted(cell))
value = cell.DateCellV
// Numeric type
value = cell.NumericCellV
case CellType.Boolean:
// Boolean type
value = cell.BooleanCellV
// String type
value = cell.StringCellV
catch (Exception)
value = &&;
特别注意的是CellType中没有Date,而日期类型的数据类型是Numeric,其实日期的数据在Excel中也是以数字的形式存储。可以使用DateUtil.IsCellDateFormatted方法来判断是否是日期类型。
有了GetCellValue方法,写数据到Excel中的时候就要有SetCellValue方法,缺的类型可以自己补。
//根据数据类型设置不同类型的cell
public void SetCellValue(ICell cell, object obj)
if (obj.GetType() == typeof(int))
cell.SetCellValue((int)obj);
else if (obj.GetType() == typeof(double))
cell.SetCellValue((double)obj);
else if (obj.GetType() == typeof(IRichTextString))
cell.SetCellValue((IRichTextString)obj);
else if (obj.GetType() == typeof(string))
cell.SetCellValue(obj.ToString());
else if (obj.GetType() == typeof(DateTime))
cell.SetCellValue((DateTime)obj);
else if (obj.GetType() == typeof(bool))
cell.SetCellValue((bool)obj);
cell.SetCellValue(obj.ToString());
cell.SetCellValue()方法只有四种重载方法,参数分别是string, bool, DateTime, double, IRichTextString(公式用IRichTextString)
以下是简单的例子,更多信息可以参见官网提供的Examples。
public void WriteToExcel(string filePath)
//创建工作薄
string extension = System.IO.Path.GetExtension(filePath);
//根据指定的文件格式创建对应的类
//URL:/Programming/csharp/50.htm
if (extension.Equals(&.xls&))
wb = new HSSFWorkbook();
wb = new XSSFWorkbook();
ICellStyle style1 = wb.CreateCellStyle();//样式
style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.L//文字水平对齐方式
style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.C//文字垂直对齐方式
//设置边框
style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.T
style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.T
style1.BorderRight = NPOI.SS.UserModel.BorderStyle.T
style1.BorderTop = NPOI.SS.UserModel.BorderStyle.T
style1.WrapText =//自动换行
ICellStyle style2 = wb.CreateCellStyle();//样式
IFont font1 = wb.CreateFont();//字体
font1.FontName = &楷体&;
font1.Color = HSSFColor.Red.I//字体颜色
font1.Boldweight = (short)FontBoldWeight.N//字体加粗样式
style2.SetFont(font1);//样式里的字体设置具体的字体样式
//设置背景色
style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.I
style2.FillPattern = FillPattern.SolidF
style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.I
style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.L//文字水平对齐方式
style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.C//文字垂直对齐方式
//创建一个表单
ISheet sheet = wb.CreateSheet(&Sheet0&);
//设置列宽
int[] columnWidth = { 10, 10, 10, 20 };
//测试数据
int rowCount = 3, columnCount = 4;
object[,] data = {
{&列0&, &列1&, &列2&, &列3&},
{&&, 400, 5.2, 6.01},
{&&, DateTime.Today, true, &&}
for (int i = 0; i & columnWidth.L i++)
//设置列宽度,256*字符数,因为单位是1/256个字符
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
for (int i = 0; i & rowC i++)
row = sheet.CreateRow(i);//创建第i行
for (int j = 0; j & columnC j++)
cell = row.CreateCell(j);
cell.CellStyle = j % 2 == 0 ? style1 : style2;
//根据数据类型设置不同类型的cell
SetCellValue(cell, data[i, j]);
//合并单元格,如果要合并的单元格中都有数据,只会保留左上角的
//CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格
CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0);
sheet.AddMergedRegion(region);
FileStream fs = File.OpenWrite(filePath);
wb.Write(fs);
//向打开的这个xls文件中写入表并保存。
fs.Close();
catch (Exception e)
Debug.WriteLine(e.Message);
如果想要设置单元格为只读或可写,可以参考这里,实际上只需要如下两个步骤:
cell.CellStyle.IsLocked =//设置该单元格为非锁定
sheet.ProtectSheet(&password&);//保护表单,password为解锁密码
cell.CellStyle.IsLocked 默认就是true,因此第2步一定要执行,才能实现锁定单元格,对于不想锁定的单元格,就一定要设置cell.CellStyle.IsLocked = false安全检查中...
请打开浏览器的javascript,然后刷新浏览器
< 浏览器安全检查中...
还剩 5 秒&下次自动登录
现在的位置:
& 综合 & 正文
【推荐】.NET使用NPOI组件将数据导出Excel
1、NPOI官方网站:
可以到此网站上去下载最新的NPOI组件版本
2、NPOI在线学习教程(中文版):
感谢Tony Qu分享出NPOI组件的使用方法
3、.NET调用NPOI组件导入导出Excel的操作类  此NPOI操作类的优点如下:
(1)支持web及winform从DataTable导出到Excel;
(2)生成速度很快;
(3)准确判断数据类型,不会出现身份证转数值等问题;
(4)如果单页条数大于65535时会新建工作表;
(5)列宽自适应;
NPOI操作类
2 using System.D
3 using System.C
4 using System.W
5 using System.Web.S
6 using System.Web.UI;
7 using System.Web.UI.HtmlC
8 using System.Web.UI.WebC
9 using System.Web.UI.WebControls.WebP 10 using System.IO; 11 using System.T 12 using NPOI; 13 using NPOI.HPSF; 14 using NPOI.HSSF; 15 using NPOI.HSSF.UserM 16 using NPOI.HSSF.U 17 using NPOI.POIFS; 18 using NPOI.U
20 namespace mon 21 { 22
public class NPOIHelper 23
/// &summary& 25
/// DataTable导出到Excel文件 26
/// &/summary& 27
/// &param name="dtSource"&源DataTable&/param& 28
/// &param name="strHeaderText"&表头文本&/param& 29
/// &param name="strFileName"&保存位置&/param& 30
public static void Export(DataTable dtSource, string strHeaderText, string strFileName) 31
using (MemoryStream ms = Export(dtSource, strHeaderText)) 33
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) 35
byte[] data = ms.ToArray(); 37
fs.Write(data, 0, data.Length); 38
fs.Flush(); 39
/// &summary& 44
/// DataTable导出到Excel的MemoryStream 45
/// &/summary& 46
/// &param name="dtSource"&源DataTable&/param& 47
/// &param name="strHeaderText"&表头文本&/param& 48
public static MemoryStream Export(DataTable dtSource, string strHeaderText) 49
HSSFWorkbook workbook = new HSSFWorkbook(); 51
HSSFSheet sheet = workbook.CreateSheet(); 52
#region 右击文件 属性信息 54
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 56
pany = "NPOI"; 57
workbook.DocumentSummaryInformation = 58
SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 60
si.Author = "文件作者信息"; //填加xls文件作者信息 61
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 62
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 63
si.Comments = "作者信息"; //填加xls文件作者信息 64
si.Title = "标题信息"; //填加xls文件标题信息 65
si.Subject = "主题信息";//填加文件主题信息 66
si.CreateDateTime = DateTime.N 67
workbook.SummaryInformation = 68
#endregion 70
HSSFCellStyle dateStyle = workbook.CreateCellStyle(); 72
HSSFDataFormat format = workbook.CreateDataFormat(); 73
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 74
//取得列宽 76
int[] arrColWidth = new int[dtSource.Columns.Count]; 77
foreach (DataColumn item in dtSource.Columns) 78
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).L 80
for (int i = 0; i & dtSource.Rows.C i++) 82
for (int j = 0; j & dtSource.Columns.C j++) 84
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).L 86
if (intTemp & arrColWidth[j]) 87
arrColWidth[j] = intT 89
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows) 98
#region 新建表,填充表头,填充列头,样式100
if (rowIndex == 65535 || rowIndex == 0)101
if (rowIndex != 0)103
sheet = workbook.CreateSheet();105
#region 表头及样式108
HSSFRow headerRow = sheet.CreateRow(0);110
headerRow.HeightInPoints = 25;111
headerRow.CreateCell(0).SetCellValue(strHeaderText);112 113
HSSFCellStyle headStyle = workbook.CreateCellStyle();114
headStyle.Alignment = CellHorizontalAlignment.CENTER;115
HSSFFont font = workbook.CreateFont();116
font.FontHeightInPoints = 20;117
font.Boldweight = 700;118
headStyle.SetFont(font);119
headerRow.GetCell(0).CellStyle = headS120
sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));121
headerRow.Dispose();122
#endregion124 125 126
#region 列头及样式127
HSSFRow headerRow = sheet.CreateRow(1); 131
HSSFCellStyle headStyle = workbook.CreateCellStyle();132
headStyle.Alignment = CellHorizontalAlignment.CENTER;133
HSSFFont font = workbook.CreateFont();134
font.FontHeightInPoints = 10;135
font.Boldweight = 700;136
headStyle.SetFont(font); 139
foreach (DataColumn column in dtSource.Columns)140
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);142
headerRow.GetCell(column.Ordinal).CellStyle = headS143 144
//设置列宽145
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 147
headerRow.Dispose();149
#endregion151 152
rowIndex = 2;153
#endregion155 156 157
#region 填充内容158
HSSFRow dataRow = sheet.CreateRow(rowIndex);159
foreach (DataColumn column in dtSource.Columns)160
HSSFCell newCell = dataRow.CreateCell(column.Ordinal);162 163
string drValue = row[column].ToString();164 165
switch (column.DataType.ToString())166
case "System.String"://字符串类型168
newCell.SetCellValue(drValue);169
case "System.DateTime"://日期类型171
DateTime dateV;172
DateTime.TryParse(drValue, out dateV);173
newCell.SetCellValue(dateV);174 175
newCell.CellStyle = dateS//格式化显示176
case "System.Boolean"://布尔型178
bool boolV = false;179
bool.TryParse(drValue, out boolV);180
newCell.SetCellValue(boolV);181
case "System.Int16"://整型183
case "System.Int32":184
case "System.Int64":185
case "System.Byte":186
int intV = 0;187
int.TryParse(drValue, out intV);188
newCell.SetCellValue(intV);189
case "System.Decimal"://浮点型191
case "System.Double":192
double doubV = 0;193
double.TryParse(drValue, out doubV);194
newCell.SetCellValue(doubV);195
case "System.DBNull"://空值处理197
newCell.SetCellValue("");198
default:200
newCell.SetCellValue("");201
#endregion206 207
rowIndex++;208
using (MemoryStream ms = new MemoryStream())212
workbook.Write(ms);214
ms.Flush();215
ms.Position = 0;216 217
sheet.Dispose();218
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet219
/// &summary&225
/// 用于Web导出226
/// &/summary&227
/// &param name="dtSource"&源DataTable&/param&228
/// &param name="strHeaderText"&表头文本&/param&229
/// &param name="strFileName"&文件名&/param&230
public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)231
HttpContext curContext = HttpContext.C234 235
// 设置编码和附件格式236
curContext.Response.ContentType = "application/vnd.ms-excel";237
curContext.Response.ContentEncoding = Encoding.UTF8;238
curContext.Response.Charset = "";239
curContext.Response.AppendHeader("Content-Disposition",240
"filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));241 242
curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());243
curContext.Response.End(); 245
/// &summary&读取excel249
/// 默认第一行为标头250
/// &/summary&251
/// &param name="strFileName"&excel文档路径&/param&252
/// &returns&&/returns&253
public static DataTable Import(string strFileName)254
DataTable dt = new DataTable();256 257
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))259
hssfworkbook = new HSSFWorkbook(file);261
HSSFSheet sheet = hssfworkbook.GetSheetAt(0);263
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();264 265
HSSFRow headerRow = sheet.GetRow(0);266
int cellCount = headerRow.LastCellN267 268
for (int j = 0; j & cellC j++)269
HSSFCell cell = headerRow.GetCell(j);271
dt.Columns.Add(cell.ToString());272
for (int i = (sheet.FirstRowNum + 1); i &= sheet.LastRowN i++)275
HSSFRow row = sheet.GetRow(i);277
DataRow dataRow = dt.NewRow();278 279
for (int j = row.FirstCellN j & cellC j++)280
if (row.GetCell(j) != null)282
dataRow[j] = row.GetCell(j).ToString();283
dt.Rows.Add(dataRow);286
4、NPOI操作类的调用方法
DataTable dt_Grade = Tools.Data.GetDataTable(strSQL);
filename += "绩效考核结果分数统计表";
mon.NPOIHelper.ExportByWeb(dt_Grade, filename, filename+".xls");
5、效果展示
6、NPOI类库下载:
信息来源:/yongfa365/archive//NPOI-MyXls-DataTable-To-Excel-From-Excel.html
&&&&推荐文章:
【上篇】【下篇】.NET/SQL/Windows
一、NPOI介绍:
使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作
二、安装NPOI
新建控制台应用程序&管理NuGet程序包&搜索NPOI&安装NPOI
三.下面是我需要的读取的Excel文件,数据格式如下:
四.添加ExcelHelper类:
using NPOI.SS.UserM
using NPOI.XSSF.UserM
using NPOI.HSSF.UserM
using System.IO;
using System.D
namespace NPOI.ReadExcel
public class ExcelHelper : IDisposable
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool
public ExcelHelper(string fileName)
this.fileName = fileN
disposed = false;
/// &summary&
/// 将DataTable数据导入到excel中
/// &/summary&
/// &param name="data"&要导入的数据&/param&
/// &param name="isColumnWritten"&DataTable的列名是否要导入&/param&
/// &param name="sheetName"&要导入的excel的sheet的名称&/param&
/// &returns&导入数据行数(包含列名那一行)&/returns&
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") & 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") & 0) // 2003版本
workbook = new HSSFWorkbook();
if (workbook != null)
sheet = workbook.CreateSheet(sheetName);
return -1;
if (isColumnWritten == true) //写入DataTable的列名
IRow row = sheet.CreateRow(0);
for (j = 0; j & data.Columns.C ++j)
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
count = 1;
count = 0;
for (i = 0; i & data.Rows.C ++i)
IRow row = sheet.CreateRow(count);
for (j = 0; j & data.Columns.C ++j)
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
workbook.Write(fs); //写入到excel
catch (Exception ex)
Console.WriteLine("Exception: " + ex.Message);
return -1;
/// &summary&
/// 将excel中的数据导入到DataTable中
/// &/summary&
/// &param name="sheetName"&excel工作薄sheet的名称&/param&
/// &param name="isFirstRowColumn"&第一行是否是DataTable的列名&/param&
/// &returns&返回的DataTable&/returns&
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") & 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") & 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
sheet = workbook.GetSheetAt(0);
sheet = workbook.GetSheetAt(0);
if (sheet != null)
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellN //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
for (int i = firstRow.FirstCellN i & cellC ++i)
ICell cell = firstRow.GetCell(i);
if (cell != null)
string cellValue = cell.StringCellV
if (cellValue != null)
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
startRow = sheet.FirstRowNum + 1;
startRow = sheet.FirstRowN
//最后一列的标号
int rowCount = sheet.LastRowN
for (int i = startR i &= rowC ++i)
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null       
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellN j & cellC ++j)
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
data.Rows.Add(dataRow);
catch (Exception ex)
Console.WriteLine("Exception: " + ex.Message);
return null;
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
protected virtual void Dispose(bool disposing)
if (!this.disposed)
if (disposing)
if (fs != null)
fs.Close();
fs = null;
disposed = true;
ExcelHelper
五,读取文件到DataTable:
using System.Collections.G
using System.D
using System.L
using System.T
using System.Threading.T
namespace NPOI.ReadExcel
class Program
static void Main(string[] args)
ExcelHelper excel_helper = new ExcelHelper(AppDomain.CurrentDomain.BaseDirectory + "test.xlsx");
DataTable dt = excel_helper.ExcelToDataTable("",true);
List&string& tableList=GetColumnsByDataTable(dt);
for (int i = 0; i & tableList.C i++)
foreach (DataRow item in dt.Rows)
if (item[0].ToString() != "")
if (i & tableList.Count - 1 & item[i + 1].ToString()!="")
Console.WriteLine(item[0].ToString()+"\t"+item[i+1].ToString());
catch (Exception ex)
Console.WriteLine("");
Console.ReadKey();
/// &summary&
/// 根据datatable获得列名
/// &/summary&
/// &param name="dt"&表对象&/param&
/// &returns&返回结果的数据列数组&/returns&
public static List&string& GetColumnsByDataTable(DataTable dt)
List&string& strColumns =new List&string& ();
if (dt.Columns.Count & 0)
int columnNum = 0;
columnNum = dt.Columns.C;
for (int i = 0; i & dt.Columns.C i++)
strColumns.Add(dt.Columns[i].ColumnName);
return strC
阅读(...) 评论()

我要回帖

更多关于 phpexcel读取时间格式 的文章

 

随机推荐