.NET使用NPOI2.0導入導出Excel

NPOI開源地址:http://npoi.codeplex.com/html

NPOI教程: http://tonyqus.sinaapp.com/java

具體的不在這裏寫了,感興趣的能夠去官網。app

先來講導出的例子post

private void ExportExcel()
        {
            DataTable table_data = MAYIXUE.BLL.NPOIUtility.GetValue();

            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet1 = hssfworkbook.CreateSheet("mayixue的NPOI測試1");

            ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
            ICellStyle stringStyle = hssfworkbook.CreateCellStyle();
            stringStyle.VerticalAlignment = VerticalAlignment.CENTER;

            //取得列寬
            int columnCount = table_data.Columns.Count;
            int[] arrColWidth = new int[columnCount];
            int width = 10;
            foreach (DataColumn column in table_data.Columns)
            {
                arrColWidth[column.Ordinal] = width;
            }

            int rowIndex = 0;
            string temp_col1 = "";
            int col1_s = 0;

            foreach (DataRow row in table_type.Rows)
            {
                #region 新建表,填充列頭,樣式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet1 = hssfworkbook.CreateSheet();
                    }

                    #region 列頭及樣式 IRow headerRow = sheet1.CreateRow(0);

                    ICellStyle headStyle = hssfworkbook.CreateCellStyle();
                    headStyle.Alignment = HorizontalAlignment.CENTER;
                    headStyle.VerticalAlignment = VerticalAlignment.CENTER;

                    IFont font = hssfworkbook.CreateFont();
                    font.FontHeightInPoints = 10;
                    font.Boldweight = 700;
                    headStyle.SetFont(font);

                    foreach (DataColumn column in table_type.Columns)
                    {
                        headerRow.CreateCell(column.Ordinal).SetCellValue(Convert.ToInt32(column.ColumnName));

                        headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                        sheet1.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);//設置列寬

                    }

                    #endregion

                    rowIndex = 1;
                }
                #endregion


                #region 填充內容

                int j = 1;
                IRow dataRow = sheet1.CreateRow(rowIndex);
                foreach (DataColumn column in table_data.Columns)
                {
                    ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
                        case "System.String"://字符串類型
                            newCell.SetCellValue(drValue);
                            newCell.CellStyle = stringStyle;
                            break;
                        case "System.Double":
                            if (drValue != "")
                            {
                                double doubV = 0;
                                double.TryParse(drValue, out doubV);
                                newCell.SetCellValue(doubV);
                            }
                            else
                            {
                                newCell.SetCellValue("");
                            }
                            newCell.CellStyle = cellStyle;
                            break;
                    }

                    #region 單元格合併(這裏只合並第一列)

                        if (j == 1 && temp_col1 != drValue) 
                        {
                            if (temp_col1 != "")
                            {
                                sheet1.AddMergedRegion(new CellRangeAddress(col1_s, rowIndex - 1, 0, 0));
                            }
                            temp_c1 = drValue;
                            col1_s = rowIndex;
                        }
                   
                    #endregion

                    j++;
                }
                #endregion

                rowIndex++;
            }

            //凍結窗口  鎖定表頭和第一列
            sheet1.CreateFreezePane(1, 1, 1, 1);

            //輸出
            context.Response.ContentType = "application/vnd.ms-excel";
            context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "mayixue的NPOI測試.xls"));
            context.Response.Clear();

            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            file.WriteTo(context.Response.OutputStream);
            context.Response.End();
        }

 

再來看下導入Excel到DataTable測試

/// <summary>  
        /// 讀取Excel文件到DataSet中  
        /// </summary>  
        /// <param name="filePath">文件路徑</param>  
        /// <returns></returns>  
        private DataTable ExcelToDataTable(string filePath)
        {
            DataTable dt = new DataTable();

            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

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

                dt.Rows.Add(dataRow);
            }
            return dt;
        }

 NPOI升級後語法上有些變更(這個例子中紅色標註地方),(我是從1.2.2直接更新到2.0的,期間發生過什麼這裏不作描述)ui

 

這個例子的實現,離不開優秀文章的幫助,在這裏向做者表示感謝。url

參考文章:spa

.net 使用NPOI或MyXls把DataTable導出到Excel

NPOI - Initialisation of record 0x862 left 2 bytes remaining still to be read.

 

POI設置EXCEL單元格格式爲文本、小數、百分比、貨幣、日期、科學計數法和中文大寫

用NPOI操做EXCEL--鎖定列

相關文章
相關標籤/搜索