<转>Npoi导入导出Excel操作<载>

 1 //Datatable导出Excel
 2 private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName)
 3         {
 4             try
 5             {
 6 HSSFWorkbook workbook = new HSSFWorkbook();
 7                 ISheet sheet = workbook.CreateSheet("Sheet1");
 8
 9                 ICellStyle HeadercellStyle = workbook.CreateCellStyle();
10                 HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
11                 HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
12                 HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
13                 HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
14                 HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
15                 //字体
16                 NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
17                 headerfont.Boldweight = (short)FontBoldWeight.Bold;
18                 HeadercellStyle.SetFont(headerfont);
19
20
21                 //用column name 作为列名
22                 int icolIndex = 0;
23                 IRow headerRow = sheet.CreateRow(0);
24                 foreach (DataColumn item in dt.Columns)
25                 {
26                     ICell cell = headerRow.CreateCell(icolIndex);
27                     cell.SetCellValue(item.ColumnName);
28                     cell.CellStyle = HeadercellStyle;
29                     icolIndex++;
30                 }
31
32                 ICellStyle cellStyle = workbook.CreateCellStyle();
33
34                 //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
35                 cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
36                 cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
37                 cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
38                 cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
39                 cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
40
41
42                 NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
43                 cellfont.Boldweight = (short)FontBoldWeight.Normal;
44                 cellStyle.SetFont(cellfont);
45
46                 //建立内容行
47                 int iRowIndex = 1;
48                 int iCellIndex = 0;
49                 foreach (DataRow Rowitem in dt.Rows)
50                 {
51                     IRow DataRow = sheet.CreateRow(iRowIndex);
52                     foreach (DataColumn Colitem in dt.Columns)
53                     {
54
55                         ICell cell = DataRow.CreateCell(iCellIndex);
56                         cell.SetCellValue(Rowitem[Colitem].ToString());
57                         cell.CellStyle = cellStyle;
58                         iCellIndex++;
59                     }
60                     iCellIndex = 0;
61                     iRowIndex++;
62                 }
63
64                 //自适应列宽度
65                 for (int i = 0; i < icolIndex; i++)
66                 {
67                     sheet.AutoSizeColumn(i);
68                 }
69
70                 //写Excel
71                 FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
72                 workbook.Write(file);
73                 file.Flush();
74                 file.Close();
75
76                 MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_successfully"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
77             }
78             catch (Exception ex)
79             {
80                 ILog log = LogManager.GetLogger("Exception Log");
81                 log.Error(ex.Message + Environment.NewLine + ex.StackTrace);
82                 //记录AuditTrail
83                 CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex);
84
85                 MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
86             }
87             finally { workbook = null; }
88
89         }

*********************************

/// <summary>
        /// Excel文件导成Datatable
        /// </summary>
        /// <param name="strFilePath">Excel文件目录地址</param>
        /// <param name="strTableName">Datatable表名</param>
        /// <param name="iSheetIndex">Excel sheet index</param>
        /// <returns></returns>
        public static DataTable XlSToDataTable(string strFilePath, string strTableName,int iSheetIndex)
        {

            string strExtName = Path.GetExtension(strFilePath);

            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(strTableName))
            {
                dt.TableName = strTableName;
            }

            if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
            {
                using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(file);
                    ISheet sheet = workbook.GetSheetAt(iSheetIndex);

                    //列头
                    foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
                    {
                        dt.Columns.Add(item.ToString(),typeof(string));
                    }

                    //写入内容
                    System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                    while(rows.MoveNext())
                    {
                        IRow row = (HSSFRow)rows.Current;
                        if (row.RowNum == sheet.FirstRowNum)
                        {
                            continue;
                        }

                        DataRow dr = dt.NewRow();
                        foreach (ICell item in row.Cells)
                        {
                            switch (item.CellType)
                            {
                                case CellType.Boolean:
                                    dr[item.ColumnIndex] = item.BooleanCellValue;
                                    break;
                                case CellType.Error:
                                    dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
                                    break;
                                case CellType.Formula:
                                    switch (item.CachedFormulaResultType)
                                    {
                                        case CellType.Boolean:
                                            dr[item.ColumnIndex] = item.BooleanCellValue;
                                            break;
                                        case CellType.Error:
                                            dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
                                            break;
                                        case CellType.Numeric:
                                            if (DateUtil.IsCellDateFormatted(item))
                                            {
                                                dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
                                            }
                                            else
                                            {
                                                dr[item.ColumnIndex] = item.NumericCellValue;
                                            }
                                            break;
                                        case CellType.String:
                                            string str = item.StringCellValue;
                                            if (!string.IsNullOrEmpty(str))
                                            {
                                                dr[item.ColumnIndex] = str.ToString();
                                            }
                                            else
                                            {
                                                dr[item.ColumnIndex] = null;
                                            }
                                            break;
                                        case CellType.Unknown:
                                        case CellType.Blank:
                                        default:
                                            dr[item.ColumnIndex] = string.Empty;
                                            break;
                                    }
                                    break;
                                case CellType.Numeric:
                                    if (DateUtil.IsCellDateFormatted(item))
                                    {
                                        dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
                                    }
                                    else
                                    {
                                        dr[item.ColumnIndex] = item.NumericCellValue;
                                    }
                                    break;
                                case CellType.String:
                                    string strValue = item.StringCellValue;
                                    if (string.IsNullOrEmpty(strValue))
                                    {
                                        dr[item.ColumnIndex] = strValue.ToString();
                                    }
                                    else
                                    {
                                        dr[item.ColumnIndex] = null;
                                    }
                                    break;
                                case CellType.Unknown:
                                case CellType.Blank:
                                default:
                                    dr[item.ColumnIndex] = string.Empty;
                                    break;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
           }

            return dt;
        }

。。。

转载别人的;

自己做个记录;

以后万一再用到了呢···

时间: 2024-10-26 04:54:17

<转>Npoi导入导出Excel操作<载>的相关文章

NPOI导入导出Excel

.net mvc利用NPOI导入导出excel 1.导出Excel :首先引用NPOI包,从这里下载>download(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> /// <returns></returns> public FileResult ExportStu2() { //获取list数据 var checkList = (from oc in db.Or

Excel操作--使用NPOI导入导出Excel为DataTable

1.ExcelHelper封装 1 namespace NPOI操作Excel 2 { 3 public class ExcelHelper 4 { 5 /// <summary> 6 /// DataTable转成Excel,返回一个文件流 7 /// </summary> 8 /// <param name="dataTable"></param> 9 /// <returns></returns> 10 pu

.net mvc利用NPOI导入导出excel

1.导出Excel : 首先引用NPOI包,从这里下载>download (Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> /// <returns></returns> public FileResult ExportStu2() { //获取list数据 var checkList = (from oc in db.OrganizeCustoms join o i

npoi导入导出excel (泛型)

最近新项目开始了,万能的excel又要上台工作.对于导出代码网上的确很多,合适的没有找到. 我们这边使用的ef + dapper 两套orm框架,他们有一个共同点,都是操作实体对象的.所以导出不能用万能的DataTable了.后面花了一些时间,集合众仙所长,写了一套单excel导入导出的方式.数据源为List<T> public class Excel { /// <summary> /// 导出到sheet中 /// </summary> /// <typepa

ASP.Net MVC利用NPOI导入导出Excel

因近期项目遇到所以记录一下: 1.导出Excel 首先引用NPOI包 (NPOI自行搜索下载) (Action一定要用FileResult) 1 [Localization] 2 /// <summary> 3 /// 导出Table的数据 4 /// </summary> 5 /// <returns></returns> 6 public FileResult ExportExcel() 7 { 8 //string schoolname = "

winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

1.通过NUGET管理器下载nopi,在引入命令空间 1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using NPOI.SS.UserModel; //NPOI 6 using NPOI.HSSF.Util; //NPOI 7 using NPOI.HSSF.UserModel; //NPOI 8 using NPOI.XSSF.UserModel; /

NPOI 导入导出excel 支持 03 07

因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps.但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上找到了NPOI这个开源的项目.http://npoi.codeplex.com/,引用的dll下载目录 http://npoi.codeplex.com/downloads/get/1476595 并且封装了通用的处理EXCEL 跟DataSet,DataTable的方法.方便调用 以上是代码 (当

简单回顾NPOI导入导出excel文件

当前环境.net4.0 去官方下下载:  NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入  NPOI.dll  就可以了. 接下来................................................................ 上代码......... .......................................................... /// <summary> /// 导出 /// </sum

NPOI导入导出Excel (2)

简单演示一下创建一个Workbook对象,添加一个工作表,在工作表中添加一行一列: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using Sys