【NPOI】.NET EXCEL匯入匯出開發包

來源:互聯網
上載者:User

標籤:style   io   ar   os   使用   sp   java   for   檔案   

1.匯出

   //活頁簿HSSFWorkbook

            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

   //ISheet頁

            ISheet sheet1 = hssfworkbook.CreateSheet("員工資料");

   //建立行         

            IRow rowHeader = sheet1.CreateRow(0);

   //設定第一行中的每一個儲存格

            rowHeader.CreateCell(0, CellType.STRING).SetCellValue("工號");

   //儲存

           using (Stream stream = File.OpenWrite(filename))

           {

               hssfworkbook.Write(stream);

           }

2.設定樣式

           ICellStyle cellStyle = hssfworkbook.CreateCellStyle();

            IDataFormat dataFormat = hssfworkbook.CreateDataFormat();

            cellStyle.DataFormat = dataFormat.GetFormat("yyyy\"年\"m\"月\"d\"日\""); 

//入職日期

            ICell InDateCell = rowContent.CreateCell(3, CellType.NUMERIC);

            InDateCell.CellStyle = cellStyle;

            InDateCell.SetCellValue(item.InDate); 

            //設定Excel表格

3.設定寬度

在使用NPOI技術開發自動操作EXCEL軟體時遇到不能精確設定列寬的問題。

ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

sheet1.SetColumnWidth(0,  50 * 256);   // 在EXCEL文檔中實際列寬為49.29

sheet1.SetColumnWidth(1, 100 * 256);   // 在EXCEL文檔中實際列寬為99.29

sheet1.SetColumnWidth(2, 150 * 256);   // 在EXCEL文檔中實際列寬為149.29

到此一般人應該知道問題出在哪了,解決方案如下:

ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");

sheet1.SetColumnWidth(0,  (int)((50 + 0.72) * 256));   // 在EXCEL文檔中實際列寬為50

sheet1.SetColumnWidth(1,  (int)((100 + 0.72) * 256));   // 在EXCEL文檔中實際列寬為100

sheet1.SetColumnWidth(2,  (int)((150 + 0.72) * 256));   // 在EXCEL文檔中實際列寬為150

既在要設定的實際列寬中加上列寬基數:0.72

NPOI讀寫Excel

1、整個Excel表格叫做工作表:WorkBook(工作薄),包含的叫頁(工作表):Sheet;行:Row;儲存格Cell。

2、NPOI是POI的C#版本,NPOI的行和列的index都是從0開始

3、POI讀取Excel有兩種格式一個是HSSF,另一個是XSSF。 HSSF和XSSF的區別如下:
HSSF is the POI Project‘s pure Java implementation of the Excel ‘97(-2007) file format.
XSSF is the POI Project‘s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
即:HSSF適用2007以前的版本,XSSF適用2007版本及其以上的。

下面是用NPOI讀寫Excel的例子:ExcelHelper封裝的功能主要是把DataTable中資料寫入到Excel中,或者是從Excel讀取資料到一個DataTable中。

ExcelHelper類:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using NPOI.HSSF.UserModel;using System.IO;using System.Data;namespace GMapDemo{    class ExcelHelper : IDisposable    {        private string fileName = null; //檔案名稱        private IWorkbook workbook = null;        private FileStream fs = null;        private bool disposed;        public ExcelHelper(string fileName)        {            this.fileName = fileName;            disposed = false;        }        /// <summary>        /// 將DataTable資料匯入到excel中        /// </summary>        /// <param name="data">要匯入的資料</param>        /// <param name="isColumnWritten">DataTable的列名是否要匯入</param>        /// <param name="sheetName">要匯入的excel的sheet的名稱</param>        /// <returns>匯入資料行數(包含列名那一行)</returns>        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)        {            int i = 0;            int j = 0;            int count = 0;            ISheet sheet = null;            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);            if (fileName.IndexOf(".xlsx") > 0) // 2007版本                workbook = new XSSFWorkbook();            else if (fileName.IndexOf(".xls") > 0) // 2003版本                workbook = new HSSFWorkbook();            try            {                if (workbook != null)                {                    sheet = workbook.CreateSheet(sheetName);                }                else                {                    return -1;                }                if (isColumnWritten == true) //寫入DataTable的列名                {                    IRow row = sheet.CreateRow(0);                    for (j = 0; j < data.Columns.Count; ++j)                    {                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);                    }                    count = 1;                }                else                {                    count = 0;                }                for (i = 0; i < data.Rows.Count; ++i)                {                    IRow row = sheet.CreateRow(count);                    for (j = 0; j < data.Columns.Count; ++j)                    {                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());                    }                    ++count;                }                workbook.Write(fs); //寫入到excel                return count;            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);                return -1;            }        }        /// <summary>        /// 將excel中的資料匯入到DataTable中        /// </summary>        /// <param name="sheetName">excel工作薄sheet的名稱</param>        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>        /// <returns>返回的DataTable</returns>        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)        {            ISheet sheet = null;            DataTable data = new DataTable();            int startRow = 0;            try            {                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);                if (fileName.IndexOf(".xlsx") > 0) // 2007版本                    workbook = new XSSFWorkbook(fs);                else if (fileName.IndexOf(".xls") > 0) // 2003版本                    workbook = new HSSFWorkbook(fs);                if (sheetName != null)                {                    sheet = workbook.GetSheet(sheetName);                }                else                {                    sheet = workbook.GetSheetAt(0);                }                if (sheet != null)                {                    IRow firstRow = sheet.GetRow(0);                    int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數                    if (isFirstRowColumn)                    {                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)                        {                            DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);                            data.Columns.Add(column);                        }                        startRow = sheet.FirstRowNum + 1;                    }                    else                    {                        startRow = sheet.FirstRowNum;                    }                    //最後一列的標號                    int rowCount = sheet.LastRowNum;                    for (int i = startRow; i <= rowCount; ++i)                    {                        IRow row = sheet.GetRow(i);                        if (row == null) continue; //沒有資料的行預設是null                                                       DataRow dataRow = data.NewRow();                        for (int j = row.FirstCellNum; j < cellCount; ++j)                        {                            if (row.GetCell(j) != null) //同理,沒有資料的儲存格都預設是null                                dataRow[j] = row.GetCell(j).ToString();                        }                        data.Rows.Add(dataRow);                    }                }                return data;            }            catch (Exception ex)            {                Console.WriteLine("Exception: " + ex.Message);                return null;            }        }        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        protected virtual void Dispose(bool disposing)        {            if (!this.disposed)            {                if (disposing)                {                    if (fs != null)                        fs.Close();                }                fs = null;                disposed = true;            }        }    }}

【NPOI】.NET EXCEL匯入匯出開發包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.