Advertisement
Guest User

ExcelNPOI class

a guest
Oct 31st, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.73 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Data;
  6. using NPOI;
  7. using NPOI.HPSF;
  8. using NPOI.HSSF.UserModel;
  9. using NPOI.POIFS;
  10. using NPOI.Util;
  11. using System.Collections;
  12.  
  13. namespace Alba.Desktop.Office
  14. {
  15.    /// <summary>
  16.    /// This class uses the NPOI library. Use it only with Excel versions
  17.    /// older than 2007.
  18.    /// NPOI ver. 1.2.3 -> http://NPOI.codeplex.com/
  19.    /// <remarks>This library will be deprecated in the future.Do not
  20.    /// use for further development.  </remarks>
  21.    /// </summary>
  22.    public class ExcelNPOI : IExcelManager
  23.    {
  24.  
  25.       private string m_Filename;
  26.       private FileStream m_ExcelFileStreamREAD = null;
  27.       private MemoryStream m_ExcelFileStreamWRITE = null;
  28.       HSSFWorkbook m_CurrWorkbook = null;
  29.  
  30.       public string Filename
  31.       {
  32.          get { return this.m_Filename; }
  33.          private set { this.m_Filename = value; }
  34.       }
  35.  
  36.       private FileStream ExcelReadStream
  37.       {
  38.          get { return this.m_ExcelFileStreamREAD; }
  39.          set { this.m_ExcelFileStreamREAD = value; }
  40.       }
  41.  
  42.       private MemoryStream ExcelWriteStream
  43.       {
  44.          get { return this.m_ExcelFileStreamWRITE; }
  45.          set { this.m_ExcelFileStreamWRITE = value; }
  46.       }
  47.  
  48.       private FileStream GetInputStream()
  49.       {
  50.          if (this.m_ExcelFileStreamREAD != null)
  51.          {
  52.             return this.m_ExcelFileStreamREAD;
  53.          }
  54.          else
  55.          {
  56.             try
  57.             {
  58.                this.m_ExcelFileStreamREAD = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);
  59.                return m_ExcelFileStreamREAD;
  60.             }
  61.             catch (Exception)
  62.             {
  63.                throw new Exception("Could not open " + Filename);
  64.             }
  65.          }//else
  66.       }
  67.  
  68.       private MemoryStream GetOutputStream()
  69.       {
  70.          if (m_ExcelFileStreamWRITE != null)
  71.          {
  72.             return m_ExcelFileStreamWRITE;
  73.          }
  74.          else
  75.          {
  76.             m_ExcelFileStreamWRITE = new MemoryStream();
  77.             m_CurrWorkbook.Write(m_ExcelFileStreamWRITE);
  78.             return m_ExcelFileStreamWRITE;
  79.          }//else
  80.       }
  81.  
  82.       public ExcelNPOI()
  83.       {
  84.       }
  85.  
  86.  
  87.       public ExcelNPOI(string a_Filename, bool ForceCreate)
  88.       {
  89.          Filename = a_Filename;
  90.          FileInfo a_FileInfo = new FileInfo(Filename);
  91.  
  92.          //if ForceCreate == true then check if the file exists and delete it.
  93.          if (ForceCreate == true)
  94.          {
  95.             if (a_FileInfo.Exists == true)
  96.             {
  97.                a_FileInfo.Delete();
  98.             }
  99.             m_CurrWorkbook = new HSSFWorkbook();
  100.          }
  101.          else //check if the file exists
  102.          {
  103.             if (!a_FileInfo.Exists)
  104.             {
  105.                throw new FileNotFoundException("File not found");
  106.             }
  107.          }
  108.       }
  109.  
  110.       #region IExcelManager Members
  111.  
  112.       public bool Create()
  113.       {
  114.          return true;
  115.       }
  116.  
  117.       public bool Create(string a_Sheet)
  118.       {
  119.          return true;
  120.       }
  121.  
  122.       public bool Open()
  123.       {
  124.          if (m_CurrWorkbook == null)
  125.          {
  126.             m_CurrWorkbook = new HSSFWorkbook(GetInputStream(), true);
  127.          }
  128.          return true;
  129.       }
  130.  
  131.       /// <summary>
  132.       /// Store's all changes made to the workbook.
  133.       /// </summary>
  134.       /// <returns></returns>
  135.       public bool Save()
  136.       {
  137.          try
  138.          {
  139.             Write(this.Filename);
  140.          }
  141.          catch (Exception e)
  142.          {
  143.             throw e;
  144.          }
  145.          return true;
  146.       }
  147.  
  148.       /// <summary>
  149.       /// Reads an entire Excel file and populates a Dataset with the data found.
  150.       /// A dataset represents the Excel file, the datatables represent the sheets
  151.       /// DataColumns are created and named after the first excel row.
  152.       /// IMPORTANT: The data columns within the Excel should be continuous!
  153.       /// </summary>
  154.       /// <returns>a DataSet holding all values found in the Excel workbook.</returns>
  155.       public DataSet ReadAll()
  156.       {
  157.          HSSFSheet a_sheet = null;
  158.          HSSFRow a_row = null;
  159.          IEnumerator a_RowEnum = null;
  160.  
  161.          Open();
  162.          //Dataset containing all Excel sheets
  163.          DataSet a_dataset = new DataSet();
  164.  
  165.          //Get all worksheets...
  166.          for (int a_SheetIndex = 0; a_SheetIndex < m_CurrWorkbook.NumberOfSheets; a_SheetIndex++)
  167.          {
  168.             a_sheet = (HSSFSheet)m_CurrWorkbook.GetSheetAt(a_SheetIndex);
  169.             //Create a new DataTable for the current sheet.
  170.             a_dataset.Tables.Add(new DataTable(a_sheet.SheetName));
  171.             //get the rows
  172.             a_RowEnum = a_sheet.GetRowEnumerator();
  173.             //for each row...
  174.             while (a_RowEnum.MoveNext())
  175.             {
  176.                //get a row
  177.                a_row = (HSSFRow)a_RowEnum.Current;
  178.  
  179.                for (int a_ColumnIndex = 0; a_ColumnIndex < a_row.LastCellNum; a_ColumnIndex++)
  180.                {
  181.                   // ---- PARSE FIRST ROW ----
  182.                   //if the rownum = 1 then instantiate a datatable for each Column header.
  183.                   //Stop when a null cell is found.
  184.                   if (a_row.RowNum == 0)
  185.                   {
  186.                      if (a_row.GetCell(a_ColumnIndex) != null)
  187.                      {
  188.                         DataColumn a_dataCol = new DataColumn(a_row.GetCell(a_ColumnIndex).ToString());
  189.                         a_dataset.Tables[a_SheetIndex].Columns.Add(a_dataCol);
  190.                      }
  191.  
  192.                   }//if
  193.                   // ---- PARSE FIRST ROW ----
  194.                   else // ---- PARSE REST ROWS.... ----
  195.                   {
  196.                      if (a_row.GetCell(a_ColumnIndex) != null)
  197.                      {
  198.                         if (a_ColumnIndex == 0)
  199.                         {
  200.                            a_dataset.Tables[a_SheetIndex].Rows.Add(a_dataset.Tables[a_SheetIndex].NewRow());
  201.                         }
  202.                         a_dataset.Tables[a_SheetIndex].Rows[a_dataset.Tables[a_SheetIndex].Rows.Count - 1][a_ColumnIndex] = a_row.GetCell(a_ColumnIndex).ToString();
  203.                      }//if
  204.                   }//else
  205.                }//for
  206.             }//while
  207.          }//for
  208.  
  209.          //Finally...
  210.          return a_dataset;
  211.       }
  212.  
  213.       public void Write(string a_Filename)
  214.       {
  215.          if (a_Filename.Trim().Length == 0)
  216.          {
  217.             return;
  218.          }
  219.          try
  220.          {
  221.             File.WriteAllBytes(a_Filename, GetOutputStream().ToArray());
  222.          }
  223.          catch (Exception)
  224.          {
  225.             throw new Exception("Could not write " + a_Filename);
  226.          }
  227.       }
  228.  
  229.       public int Replace(string a_OldValue, string a_NewValue)
  230.       {
  231.          int occurences = 0;
  232.          HSSFSheet a_sheet = null;
  233.  
  234.          Open();
  235.  
  236.          // Parse all sheets
  237.          for (int SheetIndex = 0; SheetIndex < m_CurrWorkbook.NumberOfSheets; SheetIndex++)
  238.          {
  239.             //Get the sheet
  240.             a_sheet = (HSSFSheet)m_CurrWorkbook.GetSheetAt(SheetIndex);
  241.  
  242.             //get the rows
  243.             IEnumerator a_enum = a_sheet.GetRowEnumerator();
  244.  
  245.             //Parse the rows for the value
  246.             while (a_enum.MoveNext())
  247.             {
  248.                HSSFRow arow = (HSSFRow)a_enum.Current;
  249.                //The LastCellNum property indicates the far right cell
  250.                //available in the sheet. DO NOT USE Cells.Count .
  251.                for (int i = 0; i < arow.LastCellNum; i++)
  252.                {
  253.                   if (arow.GetCell(i) != null)
  254.                   {
  255.                      if (arow.GetCell(i).ToString().Equals(a_OldValue))
  256.                      {
  257.                         arow.GetCell(i).SetCellValue(a_NewValue);
  258.                         occurences += 1;
  259.                      }
  260.                   }
  261.                }//for
  262.             }//while
  263.  
  264.          }//for
  265.          return occurences;
  266.       }
  267.  
  268.       public int Replace(string a_OldValue, string a_NewValue, string a_SheetName)
  269.       {
  270.          int occurences = 0;
  271.          HSSFSheet a_sheet = null;
  272.  
  273.          Open();
  274.  
  275.          // Parse all sheets
  276.          for (int SheetIndex = 0; SheetIndex < m_CurrWorkbook.NumberOfSheets; SheetIndex++)
  277.          {
  278.             //Get the sheet
  279.             a_sheet = (HSSFSheet)m_CurrWorkbook.GetSheetAt(SheetIndex);
  280.  
  281.             if (a_sheet.SheetName.Equals(a_SheetName))
  282.             {
  283.                //get the rows
  284.                IEnumerator a_enum = a_sheet.GetRowEnumerator();
  285.  
  286.                //Parse the rows for the value
  287.                int aint = 0;
  288.                while (a_enum.MoveNext())
  289.                {
  290.                   Console.WriteLine(aint);
  291.                   aint += 1;
  292.                   HSSFRow arow = (HSSFRow)a_enum.Current;
  293.                   //The LastCellNum property indicates the far right cell
  294.                   //available in the sheet.DO NOT USE Cells.Count.
  295.                   for (int i = 0; i < arow.LastCellNum; i++)
  296.                   {
  297.                      if (arow.GetCell(i) != null)
  298.                      {
  299.                         if (arow.GetCell(i).ToString().Equals(a_OldValue))
  300.                         {
  301.                            arow.GetCell(i).SetCellValue(a_NewValue);
  302.                            occurences += 1;
  303.                         }
  304.                      }
  305.                   }//for
  306.                }//while
  307.             }//if
  308.          }//for
  309.          return occurences;
  310.       }
  311.  
  312.       /// <summary>
  313.       /// Sets a given cell's value.If the sheet referred to , does not exist
  314.       /// then it will be created.
  315.       /// </summary>
  316.       /// <param name="a_Value">the cell's value</param>
  317.       /// <param name="a_SheetName">the sheet's name in which values should be set</param>
  318.       /// <param name="a_CellRow">the row number</param>
  319.       /// <param name="a_CellColumn">the column number</param>
  320.       public void SetCellValue(string a_Value, string a_SheetName, int a_CellRow, int a_CellColumn)
  321.       {
  322.          HSSFSheet a_Sheet = null;
  323.  
  324.          Open();
  325.  
  326.          a_Sheet = (HSSFSheet)m_CurrWorkbook.GetSheet(a_SheetName);
  327.  
  328.          //Check if the sheet exists.If not then create it.
  329.          if (a_Sheet == null)
  330.          {
  331.             m_CurrWorkbook.CreateSheet(a_SheetName);
  332.             a_Sheet = (HSSFSheet)m_CurrWorkbook.GetSheet(a_SheetName);
  333.          }
  334.  
  335.          //Check if the row exists.If not then create it.
  336.          if (a_Sheet.GetRow(a_CellRow) == null)
  337.          {
  338.             a_Sheet.CreateRow(a_CellRow);
  339.          }
  340.  
  341.          //Check if the cell exists.If not then create it.
  342.          if (a_Sheet.GetRow(a_CellRow).GetCell(a_CellColumn) == null)
  343.          {
  344.             a_Sheet.GetRow(a_CellRow).CreateCell(a_CellColumn);
  345.          }
  346.  
  347.          //Finally set the value.
  348.          
  349.          a_Sheet.GetRow(a_CellRow).GetCell(a_CellColumn).SetCellValue(a_Value);
  350.       }
  351.  
  352.       /// <summary>
  353.       /// Updates a workbook with the datatable provided.
  354.       /// </summary>
  355.       /// <param name="a_Datatable"></param>
  356.       /// <returns></returns>
  357.       public bool UpdateWorkbook(DataTable a_Datatable)
  358.       {
  359.          string a_Value = "";
  360.  
  361.          if (a_Datatable == null)
  362.          {
  363.             throw new NullReferenceException("Datatable empty");
  364.          }
  365.  
  366.          //Parse all rows
  367.          for (int rowCounter = 0; rowCounter < a_Datatable.Rows.Count; rowCounter++)
  368.          {
  369.             for (int columnCounter = 0; columnCounter < a_Datatable.Columns.Count; columnCounter++)
  370.             {
  371.                //if an exception is thrown then set an empty value.
  372.                try
  373.                {
  374.                   a_Value = a_Datatable.Rows[rowCounter].ItemArray.GetValue(columnCounter).ToString();
  375.                }
  376.                catch (Exception)
  377.                {
  378.                   a_Value = "";
  379.                }
  380.                //Finally set the cell's value
  381.                SetCellValue(a_Value, a_Datatable.TableName, rowCounter, columnCounter);
  382.  
  383.             }//for
  384.          }//foreach
  385.  
  386.          //Shift all rows by +1 in order to add the column headers.
  387.          m_CurrWorkbook.GetSheet(a_Datatable.TableName).ShiftRows(0,
  388.              m_CurrWorkbook.GetSheet(a_Datatable.TableName).PhysicalNumberOfRows, 1);
  389.  
  390.          //Add the column headers
  391.          for (int columnIndex = 0; columnIndex < a_Datatable.Columns.Count; columnIndex++)
  392.          {
  393.             SetCellValue(a_Datatable.Columns[columnIndex].ColumnName, a_Datatable.TableName, 0, columnIndex);
  394.          }
  395.  
  396.          return true;
  397.       }
  398.  
  399.       public bool Search(string a_Text)
  400.       {
  401.          throw new Exception("The method or operation is not implemented.");
  402.       }
  403.  
  404.       #endregion
  405.  
  406.    }//END OF CLASS
  407. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement