第一次用这个东西,还是比较顺利,用起来也比较好 记录一下
点击下载此NPOI组件(601.6 KB)
[2010-08-10 09:34 AM; 下载次数:1]
1.引用
using NPOI;
using NPOI.HSSF;
using NPOI.DDF;
using NPOI.POIFS;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
2.主要代码
复制内容到剪贴板 程序代码
///
/// 绑定数据
///
protected void BindExcelData()
{
//先上传 再打开
HSSFWorkbook workbook = new HSSFWorkbook(this.fupFile.FileContent);
HSSFSheet sheet = workbook.GetSheetAt(0);
DataTable table = new DataTable();
HSSFRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
//一定要对单元格类型作判断 否则会报错 cannot get a string value from a numeric cell
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
{
// 如果遇到第一个空列,则不再继续向后读取
cellCount = i + 1;
break;
}
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i);
if (row == null || row.GetCell(0) == null || row.GetCell(0).ToString().Trim() == "")
{
// 如果遇到第一个空行,则不再继续向后读取
break;
}
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount - 1; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
}
}
table.Rows.Add(dataRow);
}
//workbook = null;
//sheet = null;
this.gdvList.DataSource = table;
this.gdvList.AutoGenerateColumns = true;
this.gdvList.DataBind();
gdvList.DataKeyNames = new string[] { "IMEI" };
this.gdvList.PageSize = 20000;
lblCount.Text = gdvList.Rows.Count.ToString();
}
来源:http://www.dezai.cn/blog/article.asp?id=352
3.要注意的地方
NPOI对日期格式的转换,显示出来的日期不是我们常用的yyyy-MM-dd格式,需要做特殊判断
复制内容到剪贴板 程序代码
public static string ConvertDate(string date)
{
string[] orginDate = date.Trim().Split('-');
string year = orginDate[2].ToString().Trim();
string day = orginDate[1].ToString().Trim();
string month = orginDate[0].ToString().Trim();
if (day.Length == 1)
{
day = "0" + day.ToString();
}
if (month.Length == 1)
{
month = "0" + month.ToString().Trim();
}
if (year.Length == 2)
{
year = "20" + year.ToString().Trim();
}
return year + "-" + month + "-" + day;
}