码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-10-12 18:38:34      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:

 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;
        }

。。。

转载别人的;

自己做个记录;

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

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

标签:

原文地址:http://www.cnblogs.com/love-zf/p/4872158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!