首页 > 代码库 > NPOI操作Excel 002:读取Excel

NPOI操作Excel 002:读取Excel

本文讲述如何通过NPOI来读取Excel。
需要准备的dll见:http://blog.csdn.net/yysyangyangyangshan/article/details/42614181
环境.net2.0,Excel版本2003。
NPOI读取Excel比较简单,只要抓住Excel的几个主要点即可。
一般Excel通过这几部分构成的,book,sheet页,然后是sheet页里的行列。读取Excel则是先找到book,然后book内的sheet,之后就根据sheet里的第几行第几列进行读取内容即可。
下面直接看代码。
先看一个主要用来读取Excel内容的方法。看懂这个方法后可以灵活的使用代码读取Excel的内容。
以下是将Excel表格的内容读取为一个DataTable。当然在实际中不一定需要读取为DataTable,也可以读某一行,某一列,或者某个单元格单独读取。
    /// <summary>
        /// 读取Excel保存为datatable
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        /// <param name="startRow">第几行开始读取</param>
        /// <returns></returns>
        public static DataTable DoReadExcelDataTable(string filePath,int startRow)
        {
            DataTable dt = new DataTable();


            if (!File.Exists(filePath))
            {
                return dt;
            }


            HSSFWorkbook workbook = null;


            HSSFSheet sheet = null;


            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);


            workbook = new HSSFWorkbook(fs);


            sheet = workbook.GetSheetAt(0);


            HSSFRow row1 = sheet.GetRow(startRow);


            int cellCount = row1.LastCellNum;


            //此处是读取列名的,如果不需要列名则注释此代码
            for (int i = row1.FirstCellNum; i < row1.LastCellNum; i++)
            {
                DataColumn columItem = new DataColumn(row1.GetCell(i).StringCellValue);
                dt.Columns.Add(columItem);
            }


            int rowCount = sheet.LastRowNum;


            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                HSSFRow row = sheet.GetRow(i);


                DataRow dtrow = dt.NewRow();


                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dtrow[j] = row.GetCell(j).ToString();
                    }
                }


                dt.Rows.Add(dtrow);
            }
            sheet = null;


            workbook = null;


            return dt;
        }
如上代码,读取Excel只需要按照BOOK-SHEET-ROW或者CELL即可取出你想要的内容。

下面通过一个例子来详细看一下如何读取的。
例如,将如下Excel内容读完全取出来,并显示在页面上。
技术分享
这个代码如下:
读取Excel方法的类:
 public class NPOIHelper
    {
        /// <summary>
        /// 读取Excel保存为datatable
        /// </summary>
        /// <param name="filePath">Excel文件路径</param>
        /// <param name="startRow">第几行开始读取</param>
        /// <returns></returns>
        public static DataTable DoReadExcelDataTable(string filePath,int startRow)
        {
            DataTable dt = new DataTable();


            if (!File.Exists(filePath))
            {
                return dt;
            }


            HSSFWorkbook workbook = null;


            HSSFSheet sheet = null;


            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);


            workbook = new HSSFWorkbook(fs);


            sheet = workbook.GetSheetAt(0);


            HSSFRow row1 = sheet.GetRow(startRow);


            int cellCount = row1.LastCellNum;


            //此处是读取列名的,如果不需要列名则注释此代码
            for (int i = row1.FirstCellNum; i < row1.LastCellNum; i++)
            {
                DataColumn columItem = new DataColumn(row1.GetCell(i).StringCellValue);
                dt.Columns.Add(columItem);
            }


            int rowCount = sheet.LastRowNum;


            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                HSSFRow row = sheet.GetRow(i);


                DataRow dtrow = dt.NewRow();


                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dtrow[j] = row.GetCell(j).ToString();
                    }
                }


                dt.Rows.Add(dtrow);
            }
            sheet = null;


            workbook = null;


            return dt;
        }
    }

后台代码:
   public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialPage();
            }
        }


        private void InitialPage()
        {
            string excelFile = HttpRuntime.AppDomainAppPath.ToString();


            excelFile += @"\ExcelFile\TestNPOIRead.xls";


            DataTable dt = NPOIHelper.DoReadExcelDataTable(excelFile, 0);


            dgExcelDatas.DataSource = dt;


            dgExcelDatas.DataBind();
        }
    }

 前台显示代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestNOPIReadExcel._Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:GridView ID="dgExcelDatas" runat="server" EnableViewState="false" CellPadding="4"
       GridLines="Horizontal" PageChange="TextBox" AutoGenerateColumns="False" SortMode="Total" ForeColor="#333333"
       CellSpacing="1" Width="60%" ShowNoRecordTip="True">
     <Columns>


       <asp:TemplateField>
       <ItemTemplate>
         <span> <%#Eval("序号")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>序号</span>
       </HeaderTemplate>
       </asp:TemplateField>


       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("姓名")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>姓名</span>
       </HeaderTemplate>
       </asp:TemplateField>


        <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("年龄")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>年龄</span>
       </HeaderTemplate>
       </asp:TemplateField>
      
       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("部门")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>部门</span>
       </HeaderTemplate>
       </asp:TemplateField>


       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("职位")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>职位</span>
       </HeaderTemplate>
       </asp:TemplateField>


       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("年终奖(万)")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>年终奖(万)</span>
       </HeaderTemplate>
       </asp:TemplateField>


       <asp:TemplateField>
       <ItemTemplate>
        <span> <%#Eval("备注")%></span>
       </ItemTemplate>
       <HeaderTemplate>
       <span>备注</span>
       </HeaderTemplate>
       </asp:TemplateField>
          
     </Columns>
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <RowStyle HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    </asp:GridView>
    </div>
    </form>
</body>
</html>

效果图如下:
技术分享

工程代码下载:http://download.csdn.net/detail/yysyangyangyangshan/8351175

NPOI操作Excel 002:读取Excel