当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.Net使用Npoi导入导出Excel的方法

Asp.Net使用Npoi导入导出Excel的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

权志龙官网,星际浩劫2在线观看,周苏华

asp.net针对excel文件的导入与导出是非常常见的功能之一。本文实例讲述了asp.net使用npoi导入导出excel的方法。分享给大家供大家参考之用。具体方法如下:

在使用npoi导出excel的时候,服务器可以不装任何office组件,一般在导出时用到npoi导出excel文件,所导excel也符合规范,打开时也不会有任何文件损坏之类的提示。但是在做导入时还是使用oledb的方式,这种方式的导入在服务器端似乎还是需要装office组件的。

一、npoi导出/下载excel

具体功能代码如下:

public void npoiexcel(datatable dt, string title)
{
  npoi.hssf.usermodel.hssfworkbook book = new npoi.hssf.usermodel.hssfworkbook();
  npoi.ss.usermodel.isheet sheet = book.createsheet("sheet1");

  npoi.ss.usermodel.irow headerrow = sheet.createrow(0);
  icellstyle style = book.createcellstyle();
  style.alignment = horizontalalignment.center;
  style.verticalalignment = verticalalignment.center;

  for (int i = 0; i < dt.columns.count; i++)
  {
 icell cell = headerrow.createcell(i);
 cell.cellstyle = style;
 cell.setcellvalue(dt.columns[i].columnname);

  }

  memorystream ms = new memorystream();
  book.write(ms);
  response.addheader("content-disposition", string.format("attachment; filename={0}.xls", httputility.urlencode(title + "_" + datetime.now.tostring("yyyy-mm-dd"), system.text.encoding.utf8)));
  response.binarywrite(ms.toarray());
  response.end();
  book = null;
  ms.close();
  ms.dispose();
}

二、asp.net导入excel

导入仍然是用oledb这种方式,感兴趣的朋友可以尝试一下其他方法。

具体功能代码如下:

/// <summary>
/// 连接excel 读取excel数据  并返回dataset数据集合
/// </summary>
/// <param name="filepath">excel服务器路径</param>
/// <param name="tablename">excel表名称</param>
/// <returns></returns>
public static system.data.dataset excelsqlconnection(string filepath, string tablename)
{

  string strcon = "provider=microsoft.jet.oledb.4.0;data source=" + filepath + ";extended properties='excel 8.0;hdr=yes;imex=1'";
  oledbconnection excelconn = new oledbconnection(strcon);
  try
  {
 string strcom = string.format("select * from [sheet1$]");
 excelconn.open();
 oledbdataadapter mycommand = new oledbdataadapter(strcom, excelconn);
 dataset ds = new dataset();
 mycommand.fill(ds, "[" + tablename + "$]");
 excelconn.close();
 return ds;
  }
  catch
  {
 excelconn.close();
 return null;
  }
}

相信本文所述对大家的asp.net程序设计有一定的借鉴价值。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网