NPOI.dll 用法。單元格,樣式,字體,顏色,行高,寬度。讀寫excel


1.25 NPOI.dll

using System;


using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

using NPOI.HSSF.UserModel;

using NPOI.HPSF;

using NPOI.POIFS.FileSystem;

using NPOI.HSSF.Util;

using NPOI.SS.UserModel;

using System.IO;

using SqlHelPerXHC;

using NPOI.HSSF.Record.CF;

namespace Excl

{

    public partial class Form1 : Form

    {

        //http://tonyqus.sinaapp.com/page/4  官網使用說明

        public Form1()

        {

            InitializeComponent();

        }

        #region 定義單元格常用到樣式的枚舉

        public enum stylexls

        {

            頭,

            url,

            時間,

            數字,

            錢,

            百分比,

            中文大寫,

            科學計數法,

            默認

        }

        #endregion







        #region 定義單元格常用到樣式

        static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)

        {

            ICellStyle cellStyle = wb.CreateCellStyle();




            //定義幾種字體

            //也可以一種字體,寫一些公共屬性,然后在下面需要時加特殊的

            IFont font12 = wb.CreateFont();

            font12.FontHeightInPoints = 10;

            font12.FontName = "微軟雅黑";




            

            IFont font = wb.CreateFont();

            font.FontName = "微軟雅黑";

            //font.Underline = 1;下划線







            IFont fontcolorblue = wb.CreateFont();

            fontcolorblue.Color = HSSFColor.OLIVE_GREEN.BLUE.index;

            fontcolorblue.IsItalic = true;//下划線

            fontcolorblue.FontName = "微軟雅黑";







            //邊框

            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.DOTTED;

            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.HAIR;

            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.HAIR;

            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.DOTTED;

            //邊框顏色

            cellStyle.BottomBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;

            cellStyle.TopBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;




            //背景圖形,我沒有用到過。感覺很丑

            //cellStyle.FillBackgroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;

            //cellStyle.FillForegroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;

            cellStyle.FillForegroundColor = HSSFColor.WHITE.index;

            // cellStyle.FillPattern = FillPatternType.NO_FILL;

            cellStyle.FillBackgroundColor = HSSFColor.MAROON.index;

            

            //水平對齊

            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;




            //垂直對齊

            cellStyle.VerticalAlignment = VerticalAlignment.CENTER;




            //自動換行

            cellStyle.WrapText = true;




            //縮進;當設置為1時,前面留的空白太大了。希旺官網改進。或者是我設置的不對

            cellStyle.Indention = 0;




            //上面基本都是設共公的設置

            //下面列出了常用的字段類型

            switch (str)

            {

                case stylexls.頭:

                    // cellStyle.FillPattern = FillPatternType.LEAST_DOTS;

                    cellStyle.SetFont(font12);

                    break;

                case stylexls.時間:

                    IDataFormat datastyle = wb.CreateDataFormat();




                    cellStyle.DataFormat = datastyle.GetFormat("yyyy/mm/dd");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.數字:

                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.錢:

                    IDataFormat format = wb.CreateDataFormat();

                    cellStyle.DataFormat = format.GetFormat("¥#,##0");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.url:

                    fontcolorblue.Underline = 1;

                    cellStyle.SetFont(fontcolorblue);

                    break;

                case stylexls.百分比:

                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.中文大寫:

                    IDataFormat format1 = wb.CreateDataFormat();

                    cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.科學計數法:

                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");

                    cellStyle.SetFont(font);

                    break;

                case stylexls.默認:

                    cellStyle.SetFont(font);

                    break;

            }

            return cellStyle;







        }

        #endregion

        

        //從數據庫讀取數據寫入到excel中

        private void btnwrite_Click(object sender, EventArgs e)

        {

            #region 創建數據庫,表,設置單元的寬度

            //創建數據庫

            IWorkbook wb = new HSSFWorkbook();










            //創建表

            ISheet sh = wb.CreateSheet("zhiyuan");

           




            //設置單元的寬度

            sh.SetColumnWidth(0, 15 * 256);

            sh.SetColumnWidth(1, 35 * 256);

            sh.SetColumnWidth(2, 15 * 256);

            sh.SetColumnWidth(3, 10 * 256);

            #endregion







            int i = 0;







            #region 練習合並單元格 

            sh.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 3));

            IRow row0 = sh.CreateRow(0);

            row0.Height = 20 * 20;

            ICell icell1top0 = row0.CreateCell(0);

            ICell icell1top1 = row0.CreateCell(1);

            ICell icell1top2 = row0.CreateCell(2);

            ICell icell1top3 = row0.CreateCell(3);

            icell1top0.CellStyle = Getcellstyle(wb, stylexls.頭);

            icell1top0.SetCellValue("標題合並單元");

            #endregion




            i++;




            #region 設置表頭

            IRow row1 = sh.CreateRow(1);

            row1.Height = 20 * 20;




            ICell icell1top = row1.CreateCell(0);

            icell1top.CellStyle = Getcellstyle(wb, stylexls.頭);

            icell1top.SetCellValue("網站名");




            ICell icell2top = row1.CreateCell(1);

            icell2top.CellStyle = Getcellstyle(wb, stylexls.頭);

            icell2top.SetCellValue("網址");




            ICell icell3top = row1.CreateCell(2);

            icell3top.CellStyle = Getcellstyle(wb, stylexls.頭);

            icell3top.SetCellValue("百度快照");




            ICell icell4top = row1.CreateCell(3);

            icell4top.CellStyle = Getcellstyle(wb, stylexls.頭);

            icell4top.SetCellValue("百度收錄");

            #endregion




            i++;




            #region 讀取數據庫寫入表

            string sql = "select top 100 urlnam,url,bdtim,bdsl from zhiyuan";

            using (SqlDataReader dr = SqlHelper.ExecuteReaderText(sql, null))

            {

                if (dr.HasRows)

                {

                    while (dr.Read())

                    {

                        //創建行

                        IRow row = sh.CreateRow(i);

                        row.Height = 18 * 20;







                        //創建第1列

                        ICell icell = row.CreateCell(0);

                        icell.CellStyle = Getcellstyle(wb, stylexls.默認);

                        icell.SetCellValue(dr.GetValue(0).ToString());







                        //創建第2列

                        ICell icell1 = row.CreateCell(1);

                        icell1.CellStyle = Getcellstyle(wb, stylexls.url);

                        icell1.SetCellValue(dr.GetValue(1).ToString());

                        HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.URL);

                        link.Address = (dr.GetValue(1).ToString());

                        icell1.Hyperlink = (link);




                        //創建第3列

                        ICell icell2 = row.CreateCell(2);

                        icell2.CellStyle = Getcellstyle(wb, stylexls.時間);

                        icell2.SetCellValue(dr.IsDBNull(2) ? Convert.ToDateTime("1990-1-1") : dr.GetDateTime(2));




                        //創建第4列

                        ICell icell3 = row.CreateCell(3);

                        icell3.CellStyle = Getcellstyle(wb, stylexls.默認);

                        icell3.SetCellValue(dr.IsDBNull(3) ? 0 : dr.GetInt32(3));

                        i++;

                    }

                }

            }

            #endregion

           

            

            using (FileStream fs = File.OpenWrite("xxx.xls"))

            {

                wb.Write(fs);

                MessageBox.Show("Excel已經寫入成功!");

            }




        }




        //這個函數可以不看。

        private void CreateRow(IRow row, int j, SqlDataReader dr, ICellStyle cellstyle)

        {

            if (dr.GetFieldType(j).Name == "Int32")

            {







                row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetInt32(j));

            }

            else if (dr.GetFieldType(j).Name == "Int16")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetInt16(j)); }

            else if (dr.GetFieldType(j).Name == "Int64")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetInt64(j)); }

            else if (dr.GetFieldType(j).Name == "String")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? "" : dr.GetString(j)); }

            else if (dr.GetFieldType(j).Name == "DateTime")

            {




                ICell cell = row.CreateCell(j);

                cell.CellStyle = cellstyle;

                cell.SetCellValue(dr.IsDBNull(j) ? Convert.ToDateTime("1990-1-1") : dr.GetDateTime(j));




            }

            else if (dr.GetFieldType(j).Name == "Double")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetDouble(j)); }

            else if (dr.GetFieldType(j).Name == "Byte[]")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetByte(j)); }

            else if (dr.GetFieldType(j).Name == "Decimal")

            { row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? 0 : dr.GetDouble(j)); }

            else

            {




                row.CreateCell(j).SetCellValue(dr.IsDBNull(j) ? "" : dr.GetValue(j).ToString());

            }




        }




        #region 讀取excel

        private void btnreade_Click(object sender, EventArgs e)

        {

            //先創建文件流

            if (DialogResult.OK == openFileDialog1.ShowDialog())

            {

                using (FileStream fs = File.OpenRead(openFileDialog1.FileName))

                {

                    //申明數據庫對像

                    IWorkbook wk = new HSSFWorkbook(fs);




                    //獲取數據庫中的每個表

                    for (int i = 0; i < wk.NumberOfSheets; i++)

                    {

                        //申明表

                        ISheet wk1 = wk.GetSheetAt(i);




                        txtout.AppendText("====================" + wk1.SheetName + "================\r\n");




                        //獲取表的行

                        for (int j = 0; j < wk1.LastRowNum + 1; j++)

                        {

                            //申明行

                            IRow row = wk1.GetRow(j);

                            for (int k = 0; k < row.LastCellNum + 1; k++)

                            {

                                txtout.AppendText(string.Format("{0}\t", row.GetCell(k) == null ? "" : row.GetCell(k).ToString()));

                            }

                            txtout.AppendText("\r\n");

                        }

                    }




                }

            }




        }

        #endregion







        #region 把excel轉成htm

        private void button1_Click(object sender, EventArgs e)

        {

            if (DialogResult.OK == openFileDialog1.ShowDialog())

            {

                string str = htmlxsl.Gethtmlxls(openFileDialog1.FileName);

                using (FileStream fs = File.OpenWrite("1.htm"))

                {

                    byte[] b = Encoding.Default.GetBytes(str);

                    fs.Write(b, 0, b.Length);

                }

            }

        }

        #endregion

        

    }

}



生成htm的類


using System.Text;

using NPOI.HSSF.UserModel;

using NPOI.HPSF;

using NPOI.POIFS.FileSystem;

using NPOI.HSSF.Util;

using NPOI.SS.UserModel;

using System.IO;

using SqlHelPerXHC;

using NPOI.HSSF.Record.CF;

namespace Excl

{

    public static class htmlxsl

    {

        private static ISheet sht;

        public static string Gethtmlxls(string path)

        {




            IWorkbook wb = new HSSFWorkbook(new FileStream(path, FileMode.Open));

            sht = wb.GetSheet("zhiyuan");

            //取行Excel的最大行數     

            int rowsCount = sht.LastRowNum;

            //為保證Table布局與Excel一樣,這里應該取所有行中的最大列數(需要遍歷整個Sheet)。     

            //為少一交全Excel遍歷,提高性能,我們可以人為把第0行的列數調整至所有行中的最大列數。     

            int colsCount = sht.GetRow(0).LastCellNum;

            int colSpan;

            int rowSpan;

            bool isByRowMerged;

            StringBuilder table = new StringBuilder(rowsCount * 32);

            table.Append("<table border='1px'>");

            for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++)

            {

                table.Append("<tr>");

                for (int colIndex = 0; colIndex < colsCount; colIndex++)

                {

                    GetTdMergedInfo(rowIndex, colIndex, out colSpan, out rowSpan, out isByRowMerged);

                    //如果已經被行合並包含進去了就不輸出TD了。             

                    //注意被合並的行或列不輸出的處理方式不一樣,見下面一處的注釋說明了列合並后不輸出TD的處理方式。

                    if (isByRowMerged)

                    {

                        continue;

                    }

                    table.Append("<td");

                    if (colSpan > 1)

                        table.Append(string.Format(" colSpan={0}", colSpan));

                    if (rowSpan > 1)

                        table.Append(string.Format(" rowSpan={0}", rowSpan));

                    table.Append(">");

                    table.Append(sht.GetRow(rowIndex).GetCell(colIndex));

                    //列被合並之后此行將少輸出colSpan-1個TD。             

                    if (colSpan > 1)

                        colIndex += colSpan - 1;

                    table.Append("</td>");

                }

                table.Append("</tr>");

            }

            table.Append("</table>");

            return table.ToString();




        }

        /// <summary> 

        ///  獲取Table某個TD合並的列數和行數等信息。與Excel中對應Cell的合並行數和列數一致。 

        /// </summary> 

        /// <param name="rowIndex">行號</param> 

        /// <param name="colIndex">列號</param>

        ///  <param name="colspan">TD中需要合並的行數</param> 

        /// <param name="rowspan">TD中需要合並的列數</param> 

        /// <param name="rowspan">此單元格是否被某個行合並包含在內。如果被包含在內,將不輸出TD。</param> 

        /// <returns></returns> 

        private static void GetTdMergedInfo(int rowIndex, int colIndex, out int colspan, out int rowspan, out bool isByRowMerged)

        {

            colspan = 1;

            rowspan = 1;

            isByRowMerged = false;

            int regionsCuont = sht.NumMergedRegions;

            

            NPOI.SS.Util.CellRangeAddress region;

                

            for (int i = 0; i < regionsCuont; i++)

            {

                

                region = sht.GetMergedRegion(i);




                if (region.FirstRow == rowIndex && region.FirstColumn == colIndex)

                {

                    colspan = region.LastColumn - region.FirstColumn + 1;

                    rowspan = region.LastRow - region.FirstRow + 1;

                    return;

                }

                else if (rowIndex > region.FirstRow && rowIndex <= region.LastRow && colIndex >= region.FirstColumn && colIndex <= region.LastColumn)

                {

                    isByRowMerged = true;

                }

            }

        }

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM