.Net Excel操做之NPOI(一)簡介

1、NPOI簡介html

 NPOI是一個開源項目,能夠讀/寫xls,doc,ppt文件,有着普遍的應用。ide

 使用NPOI可以幫助開發者在沒有安裝微軟Office的狀況下讀寫Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。NPOI是構建在POI 3.x版本之上的,它能夠在沒有安裝Office的狀況下對Word/Excel文檔進行讀寫操做。函數

CodeFlex地址:http://npoi.codeplex.com/post

Nuget地址:https://www.nuget.org/packages/NPOI字體

2、安裝網站

Nuget命令ui

Install-Package NPOI

或者使用Nuget包管理安裝url

安裝結果:spa

3、Excel操做示例3d

1.Excel函數問題:

  • Excel 2003版本,最大行數是65536行。
    HSSFWorkbook workbook = new HSSFWorkbook();
  • Excel 2007版本以上,最大行數是1048576行。
    XSSFWorkbook workbook = new XSSFWorkbook();

2.建立Excel文件,並寫入數據

//建立工做簿
HSSFWorkbook wk = new HSSFWorkbook();
//建立名稱爲mySheet的表
ISheet tb = wk.CreateSheet("mySheet");
//建立第一行,此行爲第二行
IRow row = tb.CreateRow(1);
for (int i = 0; i < 20; i++)
{
    ICell cell = row.CreateCell(i); //建立單元格,寫入數據
    cell.SetCellValue(i);
}

//保存到文件
//打開一個xls文件,若是沒有自行建立
//若是存在則從新建立
using (FileStream fs = File.OpenWrite(LocalPathHelper.GetCurrentData() + "\\testone.xls"))
{
    wk.Write(fs);
    Console.WriteLine("導出數據成功!");
}

3.建立Excel文件並設置單元格樣式

/// <summary>
/// 建立xml 經常使用操做
/// </summary>
public static void TestTwo()
{
    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);
    int i = 0;

    #region 練習合併單元格
    sh.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 3));
    //CellRangeAddress()該方法的參數次序是:開始行號,結束行號,開始列號,結束列號。
    IRow row0 = sh.CreateRow(0);
    row0.Height = 20 * 20;
    ICell icell1top0 = row0.CreateCell(0);
    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

    using (FileStream stm = File.OpenWrite(LocalPathHelper.GetCurrentData() + "\\site.xls"))
    {
        wb.Write(stm);
        Console.WriteLine("導出數據成功");
    }
}
#region 定義單元格經常使用到樣式的枚舉
public enum stylexls
{
    頭,
    url,
    時間,
    數字,
    錢,
    百分比,
    中文大寫,
    科學計數法,
    默認
}
#endregion
#region 定義單元格經常使用到樣式
static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
{
    ICellStyle cellStyle = wb.CreateCellStyle();

    //定義幾種字體  
    //也能夠一種字體,寫一些公共屬性,而後在下面須要時加特殊的  
    IFont font12 = wb.CreateFont();
    font12.FontHeightInPoints = 12;
    font12.FontName = "微軟雅黑";


    IFont font = wb.CreateFont();
    font.FontName = "微軟雅黑";
    //font.Underline = 1;下劃線  


    IFont fontcolorblue = wb.CreateFont();
    fontcolorblue.Color = HSSFColor.OliveGreen.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.OliveGreen.Blue.Index;
    cellStyle.TopBorderColor = HSSFColor.OliveGreen.Blue.Index;

    //背景圖形,我沒有用到過。感受很醜  
    cellStyle.FillForegroundColor = HSSFColor.White.Index;
    // cellStyle.FillPattern = FillPatternType.NO_FILL;  
    cellStyle.FillBackgroundColor = HSSFColor.Blue.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 = FontUnderlineType.Single;
            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  
View Code

4.讀取Excel文件數據

        StringBuilder sbr = new StringBuilder();
        using (FileStream fs = File.OpenRead(LocalPathHelper.GetCurrentData() + "\\site.xls"))
        {
            HSSFWorkbook wk = new HSSFWorkbook(fs);//讀取xls文件中的數據寫入wk中
            for (int i = 0; i < wk.NumberOfSheets; i++) //NumberOfSheets是總共的表數 
            {
                ISheet sheet = wk.GetSheetAt(i); //讀取當前表數據
                for (int j = 0; j <= sheet.LastRowNum; j++) //LastRowNum 最後一行的索引,從0開始
                {
                    IRow row = sheet.GetRow(j);//獲取當前行數據
                    if (row != null)
                    {
                        sbr.Append("\r\n--------------------------------\r\n");
                        for (int k = 0; k <= row.LastCellNum; k++) //LastCellNum 最後一列的索引,從0開始
                        {
                            ICell cell = row.GetCell(k); //獲取當前單元格
                            if (cell != null)
                            {
                                sbr.Append(cell.ToString() + "\t");
                            }
                        }
                    }
                }
            }

        }

        //將讀取的Xml文件數據寫入到txt中
        using (StreamWriter sw = new StreamWriter(new FileStream(LocalPathHelper.GetCurrentData() + "\\test1.txt", FileMode.Append)))
        {
            sw.Write(sbr.ToString());
            sw.Flush();
            Console.WriteLine("讀取數據成功!");
        }

 

更多:

 .Net Excel操做之NPOI(二)經常使用操做封裝

C#中操做剛導出的Excel,設置其爲自動調整列寬

C#操做word封裝

相關文章
相關標籤/搜索