简单 Excel 的导入导出 (通过 NPOI)

小编 2026-07-14 阅读:221 评论:0
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text;...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json.Linq;

using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections;
using NPOI.HSSF.Util;
using System.Drawing;


/// <summary>
///ExcelHeaper 的摘要说明
/// </summary>
public class ExcelHeaper
{

    public static int thisRows = 0;
    public ExcelHeaper()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>  
    /// 将excel导入到datatable  
    /// </summary>  
    /// <param name=\"filePath\">excel路径</param>  
    /// <param name=\"isColumnName\">第一行是否是列名</param>  
    /// <returns>返回datatable</returns>  
    public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
    {

        DataTable dataTable = null;
        FileStream fs = null;
        DataColumn column = null;
        DataRow dataRow = null;
        IWorkbook workbook = null;
        ISheet sheet = null;
        IRow row = null;
        ICell cell = null;
        int startRow = 0;
        try
        {

            using (fs = File.OpenRead(filePath))
            //  using (fs = File.Copy(filePath))
            {
                // 2007版本  
                if (filePath.IndexOf(\".xlsx\") > 0)
                    workbook = new XSSFWorkbook(fs);
                // 2003版本  
                //if (filePath.IndexOf(\".xls\") > 0)
                //    workbook = new HSSFWorkbook(fs);

                if (workbook != null)
                {
                    sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet  
                  
                    dataTable = new DataTable();
                    if (sheet != null)
                    {
                        int rowCount = sheet.LastRowNum;//总行数  
                        if (rowCount > 0)
                        {
                            IRow firstRow = sheet.GetRow(0);//第一行  
                            int cellCount = firstRow.LastCellNum;//列数  

                            //构建datatable的列  
                            if (isColumnName)
                            {
                                startRow = 1;//如果第一行是列名,则从第二行开始读取  
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        if (cell.StringCellValue != null)
                                        {
                                            column = new DataColumn(cell.StringCellValue);
                                            dataTable.Columns.Add(column);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    column = new DataColumn(\"column\" + (i + 1));
                                    dataTable.Columns.Add(column);
                                }
                            }

                            //填充行  
                            for (int i = startRow; i <= rowCount; ++i)
                            {
                                row = sheet.GetRow(i);
                                if (row == null) continue;

                                dataRow = dataTable.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; ++j)
                                {
                                    cell = row.GetCell(j);
                                    if (cell == null)
                                    {
                                        dataRow[j] = \"\";
                                    }
                                    else
                                    {
                                        //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                        switch (cell.CellType)
                                        {
                                            case CellType.BLANK:
                                                dataRow[j] = \"\";
                                                break;
                                            case CellType.NUMERIC:
                                                short format = cell.CellStyle.DataFormat;
                                                //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                                if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
                                                    dataRow[j] = cell.DateCellValue;
                                                else if (format == 20 || format == 185 || format == 184)
                                                    dataRow[j] = cell.DateCellValue.ToString(\"HH:mm\");
                                                else if (format == 22)
                                                    dataRow[j] = cell.DateCellValue.ToString(\"yyyy/MM/dd HH:mm\");
                                                else
                                                    dataRow[j] = cell.NumericCellValue;
                                                break;
                                            case CellType.FORMULA:
                                                try
                                                {
                                                    dataRow[j] = cell.NumericCellValue;
                                                }
                                                catch
                                                {
                                                    dataRow[j] = cell.StringCellValue;
                                                }
                                                break;
                                            case CellType.STRING:
                                                dataRow[j] = cell.StringCellValue;
                                                break;
                                            default:
                                                dataRow[j] = cell.CellFormula;
                                                break;
                                        }
                                    }
                                }
                                dataTable.Rows.Add(dataRow);
                            }
                        }
                    }
                }
            }
            return dataTable;
        }
        catch (Exception ex)
        {
            HistoryHelper.SaveError(\"读取Excel异常\", ex.ToString());
            if (fs != null)
            {
                fs.Close();
            }
            return null;
        }
    }

    /// <summary>  
    /// 根据表名称将excel导入到datatable  
    /// </summary>  
    /// <param name=\"filePath\">excel路径</param>  
    /// <param name=\"isColumnName\">第一行是否是列名</param>  
    /// <returns>返回datatable</returns>  
    public static DataTable ExcelToDataTableByName(string filePath, bool isColumnName,string TableName)
    {

        DataTable dataTable = null;
        FileStream fs = null;
        DataColumn column = null;
        DataRow dataRow = null;
        IWorkbook workbook = null;
        ISheet sheet = null;
        IRow row = null;
        ICell cell = null;
        int startRow = 0;
        try
        {

            using (fs = File.OpenRead(filePath))
            //  using (fs = File.Copy(filePath))
            {
                // 2007版本  
                if (filePath.IndexOf(\".xlsx\") > 0)
                    workbook = new XSSFWorkbook(fs);
                // 2003版本  
                //if (filePath.IndexOf(\".xls\") > 0)
                //    workbook = new HSSFWorkbook(fs);

                if (workbook != null)
                {
                  // sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet  
                     sheet = workbook.GetSheet(TableName);//读取固定名称的sheet;

                    dataTable = new DataTable();
                    if (sheet != null)
                    {
                        int rowCount = sheet.LastRowNum;//总行数  
                        if (rowCount > 0)
                        {
                            IRow firstRow = sheet.GetRow(0);//第一行  
                            int cellCount = firstRow.LastCellNum;//列数  

                            //构建datatable的列  
                            if (isColumnName)
                            {
                                startRow = 1;//如果第一行是列名,则从第二行开始读取  
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        if (cell.StringCellValue != null)
                                        {
                                            column = new DataColumn(cell.StringCellValue);
                                            dataTable.Columns.Add(column);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    column = new DataColumn(\"column\" + (i + 1));
                                    dataTable.Columns.Add(column);
                                }
                            }

                            //填充行  
                            for (int i = startRow; i <= rowCount; ++i)
                            {
                                try
                                {
                                    row = sheet.GetRow(i);
                                    if (row == null) continue;

                                    dataRow = dataTable.NewRow();
                                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                                    {
                                        cell = row.GetCell(j);
                                        if (cell == null)
                                        {
                                            dataRow[j] = \"\";
                                        }
                                        else
                                        {
                                            //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                            switch (cell.CellType)
                                            {
                                                case CellType.BLANK:
                                                    dataRow[j] = \"\";
                                                    break;
                                                case CellType.NUMERIC:
                                                    short format = cell.CellStyle.DataFormat;
                                                    //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                                    if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
                                                        dataRow[j] = cell.DateCellValue;
                                                    else if (format == 20 || format == 185 || format == 184)
                                                        dataRow[j] = cell.DateCellValue.ToString(\"HH:mm\");
                                                    else if (format == 22)
                                                        dataRow[j] = cell.DateCellValue.ToString(\"yyyy/MM/dd HH:mm\");
                                                    else
                                                        dataRow[j] = cell.NumericCellValue;
                                                    break;
                                                case CellType.FORMULA:
                                                    try
                                                    {
                                                        dataRow[j] = cell.NumericCellValue;
                                                    }
                                                    catch
                                                    {
                                                        dataRow[j] = cell.StringCellValue;
                                                    }
                                                    break;
                                                case CellType.STRING:
                                                    dataRow[j] = cell.StringCellValue;
                                                    break;
                                                default:
                                                    dataRow[j] = cell.CellFormula;
                                                    break;
                                            }
                                        }
                                    }
                                    dataTable.Rows.Add(dataRow);
                                }
                                catch (Exception ex)
                                {
                                   HistoryHelper.SaveError(\"error\", ex.ToString());
                                   continue;
                                }
                            }
                        }
                    }
                }
            }
            return dataTable;
        }
        catch (Exception ex)
        { 
            HistoryHelper.SaveError(\"读取Excel异常\", ex.ToString());
            if (fs != null)
            {
                fs.Close();
            }
            return null;
        }
    }


    /// <summary>  
    /// 将excel导入到datatableb并跳过前面固定行数
    /// </summary>  
    /// <param name=\"filePath\">excel路径</param>  
    /// <param name=\"isColumnName\">第一行是否是列名</param>  
    /// <returns>返回datatable</returns>  
    public static DataTable ExcelToDataTable(string filePath, bool isColumnName,int rows =0)
    {

        DataTable dataTable = null;
        FileStream fs = null;
        DataColumn column = null;
        DataRow dataRow = null;
        IWorkbook workbook = null;
        ISheet sheet = null;
        IRow row = null;
        ICell cell = null;
        int startRow = 0;
        try
        {

            using (fs = File.OpenRead(filePath))
            //  using (fs = File.Copy(filePath))
            {
                // 2007版本  
                if (filePath.IndexOf(\".xlsx\") > 0)
                    workbook = new XSSFWorkbook(fs);
                // 2003版本  
                //if (filePath.IndexOf(\".xls\") > 0)
                //    workbook = new HSSFWorkbook(fs);

                if (workbook != null)
                {
                    sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet  

                    dataTable = new DataTable();
                    if (sheet != null)
                    {
                        int rowCount = sheet.LastRowNum;//总行数  

                        if (rowCount > 0)
                        {
                            IRow firstRow = sheet.GetRow(0);//第一行  
                            int cellCount = firstRow.LastCellNum;//列数  
                            thisRows = rowCount;
                            //构建datatable的列  
                            if (isColumnName)
                            {
                                startRow = 1;//如果第一行是列名,则从第二行开始读取  
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    cell = firstRow.GetCell(i);
                                    if (cell != null)
                                    {
                                        if (cell.StringCellValue != null)
                                        {
                                            column = new DataColumn(cell.StringCellValue);
                                            dataTable.Columns.Add(column);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                {
                                    column = new DataColumn(\"column\" + (i + 1));
                                    dataTable.Columns.Add(column);
                                }
                            }

                            //填充行  
                            for (int i = thisRows; i <= rowCount; i++)
                            {
                                row = sheet.GetRow(i);
                                if (row == null) continue;

                                dataRow = dataTable.NewRow();
                                for (int j = row.FirstCellNum; j < cellCount; ++j)
                                {
                                    cell = row.GetCell(j);
                                    if (cell == null)
                                    {
                                        dataRow[j] = \"\";
                                    }
                                    else
                                    {
                                        //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)  
                                        switch (cell.CellType)
                                        {
                                            case CellType.BLANK:
                                                dataRow[j] = \"\";
                                                break;
                                            case CellType.NUMERIC:
                                                short format = cell.CellStyle.DataFormat;
                                                //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理  
                                                if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
                                                    dataRow[j] = cell.DateCellValue;
                                                else if (format == 20 || format == 185 || format == 184)
                                                    dataRow[j] = cell.DateCellValue.ToString(\"HH:mm\");
                                                else if (format == 22)
                                                    dataRow[j] = cell.DateCellValue.ToString(\"yyyy/MM/dd HH:mm\");
                                                else
                                                    dataRow[j] = cell.NumericCellValue;
                                                break;
                                            case CellType.FORMULA:
                                                try
                                                {
                                                    dataRow[j] = cell.NumericCellValue;
                                                }
                                                catch
                                                {
                                                    dataRow[j] = cell.StringCellValue;
                                                }
                                                break;
                                            case CellType.STRING:
                                                dataRow[j] = cell.StringCellValue;
                                                break;
                                            default:
                                                dataRow[j] = cell.CellFormula;
                                                break;
                                        }
                                    }
                                }
                                dataTable.Rows.Add(dataRow);
                            }
                            thisRows = rowCount;
                        }
                    }
                }
            }
            return dataTable;
        }
        catch (Exception ex)
        {
            HistoryHelper.SaveError(\"读取Excel异常\", ex.ToString());
            if (fs != null)
            {
                fs.Close();
            }
            return null;
        }
    }

 
    /// <summary>
    /// 文件输出流
    /// </summary>
    /// <param name=\"bytes\"></param>
    public static  void OutputClient(byte[] bytes)
    {
        HttpResponse response = HttpContext.Current.Response;

        response.Buffer = true;

        response.Clear();
        response.ClearHeaders();
        response.ClearContent();

        response.ContentType = \"application/vnd.ms-excel\";
        response.AddHeader(\"Content-Disposition\", string.Format(\"attachment; filename={0}.xls\", DateTime.Now.ToString(\"yyyy-MM-dd-HH-mm-ss\")));

        response.Charset = \"GB2312\";
        response.ContentEncoding = Encoding.GetEncoding(\"GB2312\");

        response.BinaryWrite(bytes);
        response.Flush();

        response.Close();
    }

    /// <summary>
    /// datatable 转换为jarry
    /// </summary>
    /// <param name=\"dt\"></param>
    /// <returns></returns>
    public static JArray DataTableJArray(DataTable dt)
    {
        JArray ja = new JArray();
        foreach (DataRow row in dt.Rows)
        {
            JObject jo = new JObject();
            foreach (DataColumn col in dt.Columns)
            {
                jo[col.ColumnName] = row[col.ColumnName].ToString();
            }
            ja.Add(jo);
        }
        return ja;
    }
    /// <summary>
    /// 数据导出
    /// </summary>
    /// <param name=\"dt\"></param>
    /// <returns></returns>
    public static string GetCSV(JArray ja, Dictionary<string, object> StrDate)
    {
        HttpContext context = HttpContext.Current;

        string Code = StrDate[\"fieldCode\"].ToString();
        string Name = StrDate[\"fieldName\"].ToString();
        string ExcelName = StrDate[\"ExcelName\"].ToString();

        string[] fieldCode = Code.Split(\',\');
        string[] fieldName = Name.Split(\',\');

        JArray jaTH = new JArray();
        for (int i = 0; i < fieldCode.Length; i++)
        {
            JObject joTH = new JObject();
            joTH[\"Index\"] = i;
            joTH[\"FieldCode\"] = fieldCode[i];
            joTH[\"FieldName\"] = fieldName[i];
            joTH[\"FieldDataType\"] = \"nvarchar\";
            joTH[\"Display\"] = true;
            joTH[\"Width\"] = 100;
            joTH[\"ForeColor\"] = \"#000000\";
            joTH[\"BackColor\"] = \"#FFFFFF\";
            jaTH.Add(joTH);
        }


        
        JObject queryData = new JObject();
        queryData[\"MasterData\"] = ja;

        JObject tableHead = new JObject();
        tableHead[\"TableHeader\"] = jaTH;
        string sheetName = ExcelName + DateTime.Now.ToString(\"yyyyMMddHHmmss\");

        MemoryStream ms = new MemoryStream();
        GetExcelMemoryStream(tableHead, queryData, ms);
        ms.Flush();
        ms.Position = 0;
        context.Response.Clear();
        context.Response.Charset = \"utf-8\";
        context.Response.Buffer = false;
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.AppendHeader(\"Content-Disposition\", \"attachment;filename=\" + HttpUtility.UrlEncode(sheetName) + \".xls\");
        context.Response.BinaryWrite(ms.ToArray());
        context.ApplicationInstance.CompleteRequest();
        context.Response.End();
        ms.Close();
        return string.Empty;
    }
    /// <summary>
    /// 生成Excel写入流
    /// </summary>
    /// <param name=\"tableHead\"></param>
    /// <param name=\"queryData\"></param>
    /// <param name=\"ms\"></param>
    public static void GetExcelMemoryStream(JObject tableHead, JObject queryData, MemoryStream ms)
    {
        JArray ja = (JArray)tableHead[\"TableHeader\"];
        JArray jaTH = new JArray();
        foreach (JObject jo in ja.OrderBy(f => (int)f[\"Index\"]))
        {
            jaTH.Add(jo);
        }
        //处理把它转换成十六进制并放入一个数 
        //int[] color = new int[3];
        //color[0] = Integer.parseInt(str.substring(1, 3), 16);
        //color[1] = Integer.parseInt(str.substring(3, 5), 16);
        //color[2] = Integer.parseInt(str.substring(5, 7), 16);
        ////自定义颜色 
        //HSSFPalette palette = workbook.getCustomPalette();
        //palette.setColorAtIndex(HSSFColor.BLACK.index, (byte)color[0], (byte)color[1], (byte)color[2]);
        ////将自定义的颜色引入进来 
        //HSSFFont font = workbook.createFont();
        //font.setColor(HSSFColor.BLACK.index);
        //HSSFCellStyle cellStyle = workbook.createCellStyle();
        //cellStyle.setFont(font); 

        for (int i = jaTH.Count - 1; i >= 0; i--)
        {
            string display = jaTH[i][\"Display\"].ToString().ToUpper();
            if (display == \"FLASE\" || display == \"N\") jaTH.RemoveAt(i);
        }
        JObject joMM = (JObject)tableHead[\"ModuleMaster\"];
        JArray jaData = (JArray)queryData[\"MasterData\"];
        HSSFWorkbook hssfworkbook = new HSSFWorkbook();
        HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet(\"Sheet1\");
        //自定义颜色
        Hashtable htColor = new Hashtable();
        foreach (JObject joTH in jaTH)
        {
            string fcStr = joTH[\"ForeColor\"].ToString();
            if (fcStr != \"None\" && !htColor.ContainsKey(fcStr))
            {
                int[] fc = new int[3];
                fc[0] = Convert.ToInt32(fcStr.Substring(1, 2), 16);
                fc[1] = Convert.ToInt32(fcStr.Substring(3, 2), 16);
                fc[2] = Convert.ToInt32(fcStr.Substring(5, 2), 16);
                short fcIndex = GetXLColour(hssfworkbook, Color.FromArgb(fc[0], fc[1], fc[2]));
                htColor.Add(fcStr, fcIndex);
            }
            string bcStr = joTH[\"BackColor\"].ToString();
            if (bcStr != \"none\" && !htColor.ContainsKey(bcStr))
            {
                int[] bc = new int[3];
                bc[0] = Convert.ToInt32(bcStr.Substring(1, 2), 16);
                bc[1] = Convert.ToInt32(bcStr.Substring(3, 2), 16);
                bc[2] = Convert.ToInt32(bcStr.Substring(5, 2), 16);
                short bcIndex = GetXLColour(hssfworkbook, Color.FromArgb(bc[0], bc[1], bc[2]));
                htColor.Add(bcStr, bcIndex);
            }
        }
        //表头样式
        ICellStyle csHead = hssfworkbook.CreateCellStyle();
        csHead.WrapText = false;
        csHead.VerticalAlignment = VerticalAlignment.CENTER;
        csHead.Alignment = HorizontalAlignment.CENTER;
        csHead.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_25_PERCENT.index;
        csHead.FillPattern = FillPatternType.SOLID_FOREGROUND;
        csHead.BorderBottom = BorderStyle.THIN;
        csHead.BorderLeft = BorderStyle.THIN;
        csHead.BorderRight = BorderStyle.THIN;
        csHead.BorderTop = BorderStyle.THIN;
        //表头
        HSSFRow rowHead = (HSSFRow)sheet1.CreateRow(0);
        for (int i = 0; i < jaTH.Count; i++)
        {
            bool display = (jaTH[i][\"Display\"].ToString() != \"N\");
            if (!display) continue;
            string fieldName = jaTH[i][\"FieldName\"].ToString();
            int width = (int)jaTH[i][\"Width\"];
            sheet1.SetColumnWidth(i, (fieldName.Length + 1) * 2 * 256);
            ICell cell = rowHead.CreateCell(i, CellType.STRING);
            cell.SetCellValue(fieldName);
            cell.CellStyle = csHead;
        }
        //数据
        ICellStyle[] cellStyle = new ICellStyle[jaTH.Count];
        IFont[] font = new IFont[jaTH.Count];
        for (int r = 0; r < jaData.Count; r++)
        {
            JObject joData = (JObject)jaData[r];
            HSSFRow row = (HSSFRow)sheet1.CreateRow(r + 1);

            for (int i = 0; i < jaTH.Count; i++)
            {
                bool display = (jaTH[i][\"Display\"].ToString() != \"N\");
                if (!display) continue;
                string fcStr = jaTH[i][\"ForeColor\"].ToString();
                string bcStr = jaTH[i][\"BackColor\"].ToString();
                bool needCreateFont = (font[i] == null);
                if (needCreateFont)
                {
                    font[i] = hssfworkbook.CreateFont();
                    if (fcStr != \"none\")
                    {
                        font[i].Color = (short)htColor[fcStr];
                    }
                }
                bool needCreateCellStyle = (cellStyle[i] == null);
                if (needCreateCellStyle)
                {
                    cellStyle[i] = hssfworkbook.CreateCellStyle();
                    cellStyle[i].WrapText = true;
                    cellStyle[i].VerticalAlignment = VerticalAlignment.CENTER;
                    if (bcStr != \"none\")
                    {
                        cellStyle[i].FillForegroundColor = (short)htColor[bcStr];
                        cellStyle[i].FillPattern = FillPatternType.SOLID_FOREGROUND;
                    }
                    cellStyle[i].BorderBottom = BorderStyle.THIN;
                    cellStyle[i].BorderLeft = BorderStyle.THIN;
                    cellStyle[i].BorderRight = BorderStyle.THIN;
                    cellStyle[i].BorderTop = BorderStyle.THIN;
                    cellStyle[i].SetFont(font[i]);
                }

                string fieldCode = jaTH[i][\"FieldCode\"].ToString();
                string fieldDataType = jaTH[i][\"FieldDataType\"].ToString();
                ICell cell;
                if (fieldDataType.StartsWith(\"numeric(\"))
                {
                    string[] strAry = fieldDataType.TrimStart(\"numeric(\".ToCharArray()).TrimEnd(\')\').Trim().Split(\',\');
                    int precision = int.Parse(strAry[1]);
                    cell = row.CreateCell(i);
                    if (joData[fieldCode] != null) cell.SetCellValue(Convert.ToDouble(joData[fieldCode]));
                    if (needCreateCellStyle)
                    {
                        cellStyle[i].DataFormat = HSSFDataFormat.GetBuiltinFormat(\"0.\" + new string(\'0\', precision));
                        cellStyle[i].Alignment = HorizontalAlignment.RIGHT;
                    }
                    cell.CellStyle = cellStyle[i];

                }
                else if (fieldDataType == \"float\" || fieldDataType == \"double\" || fieldDataType == \"int\" || fieldDataType == \"decimal\")
                {
                    cell = row.CreateCell(i, CellType.NUMERIC);
                    if (joData[fieldCode] != null && joData[fieldCode].ToString() != string.Empty) cell.SetCellValue(Convert.ToDouble(joData[fieldCode]));
                    if (needCreateCellStyle)
                    {
                        cellStyle[i].Alignment = HorizontalAlignment.RIGHT;
                    }
                    cell.CellStyle = cellStyle[i];
                }
                else if (fieldDataType == \"datetime\")
                {
                    cell = row.CreateCell(i);
                    if (joData[fieldCode] != null)
                    {
                        if (joData[fieldCode].ToString() == string.Empty)
                            cell.SetCellValue(string.Empty);
                        else
                            cell.SetCellValue(Convert.ToDateTime(joData[fieldCode]));
                    }
                    IDataFormat format = hssfworkbook.CreateDataFormat();
                    if (needCreateCellStyle)
                    {
                        cellStyle[i].DataFormat = format.GetFormat(\"yyyy-MM-dd HH:mm:ss\");
                        cellStyle[i].Alignment = HorizontalAlignment.CENTER;
                    }
                    cell.CellStyle = cellStyle[i];
                }
                else if (fieldDataType == \"date\")
                {
                    cell = row.CreateCell(i);
                    if (joData[fieldCode] != null)
                    {
                        if (joData[fieldCode].ToString() == string.Empty)
                            cell.SetCellValue(string.Empty);
                        else
                            cell.SetCellValue(Convert.ToDateTime(joData[fieldCode]));
                    }
                    IDataFormat format = hssfworkbook.CreateDataFormat();
                    if (needCreateCellStyle)
                    {
                        cellStyle[i].DataFormat = format.GetFormat(\"yyyy-MM-dd\");
                        cellStyle[i].Alignment = HorizontalAlignment.CENTER;
                    }
                    cell.CellStyle = cellStyle[i];
                }
                else
                {
                    cell = row.CreateCell(i, CellType.STRING);
                    if (joData[fieldCode] != null) cell.SetCellValue(joData[fieldCode].ToString());
                    if (needCreateCellStyle)
                    {
                        cellStyle[i].Alignment = HorizontalAlignment.LEFT;
                    }
                    cell.CellStyle = cellStyle[i];
                }

            }
        }
        hssfworkbook.Write(ms);
    }
    /// <summary>
    /// 得到Excel调色板颜色索引
    /// </summary>
    /// <param name=\"workbook\"></param>
    /// <param name=\"SystemColour\"></param>
    /// <returns></returns>
    public static short GetXLColour(HSSFWorkbook workbook, System.Drawing.Color SystemColour)
    {
        short s = 0;
        HSSFPalette XlPalette = workbook.GetCustomPalette();
        HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
        if (XlColour == null)
        {
            if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
            {
                if (false && NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
                {
                    //NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE = 64;  
                    //NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;  
                    XlColour = XlPalette.AddColor(SystemColour.R, SystemColour.G, SystemColour.B);
                }
                else
                {
                    XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
                }

                s = XlColour.GetIndex();
            }

        }
        else
            s = XlColour.GetIndex();
        return s;
    }
 
        
}
 

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

热门文章
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
标签列表