[WinForm] miscellany (5): C # imported into Excel DataTable

Methods provided herein by means of NPOI (the official document: https:? //Archive.codeplex.com/ p = npoi)

Referring to a library is no longer start Excel (Excel before because there is no way to be written), then its speed is very fast.

Add this library approach is NuGet, specific steps https://www.cnblogs.com/RicardoIsLearning/p/12111040.html

After the addition is complete, the write namespace

using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;

 

Specific code into the following

private System.Data.DataTable Excel2DataTable(string filepath, int indexOfsheet = 0)
{
    System.Data.DataTable dt = new System.Data.DataTable();
    IWorkbook workbook = null;//another way: var hssfworkbook = new HSSFWorkbook(file);
    FileStream file = null;
    try {
        using (file = new FileStream(filepath, FileMode.Open, FileAccess.Read)) {

            if (filepath.IndexOf(".xlsx") > 0)
                workbook = new XSSFWorkbook(file);//read .xlsx file
            else if (filepath.IndexOf(".xls") > 0)
                workbook = new HSSFWorkbook(file);//read .xls file

            if (workbook != null) {
                //int indexOfsheet = 0;//get the 1st sheet
                ISheet sheet = workbook.GetSheetAt(indexOfsheet);
                IEnumerator rows = sheet.GetRowEnumerator();//get all rows

                //add cols
                IRow headerRow = sheet.GetRow(0); //get the row of column name
                int cellCount = headerRow.LastCellNum; //get the column number
                                                        //so that we can get all columns
                for (int i = 0; i < cellCount; i++) {
                    string ttname;
                    ttname = (sheet.GetRow(0).GetCell(i) != null) ? sheet.GetRow(0).GetCell(i).ToString() : "";
                    dt.Columns.Add(ttname, typeof(string));
                }
                ////get the assigned columns
                //int[] indexcolumns = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };//start from 0
                //for (int i = 0; j < indexcolumns.Length; i++) {
                //    string ttname;
                //    ttname = sheet.GetRow(0).GetCell(indexcolumns[i]).ToString();
                //    dt.Columns.Add(ttname, typeof(string));
                //}

                //add rows
                //for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) {}
                int irow = 0;
                while (rows.MoveNext()) {//start from the index of 0
                    if (irow == 0) {
                        irow++;
                        continue;
                    }                                
                    IRow row = (IRow)rows.Current;//IRow row = sheet.GetRow(irow);
                    System.Data.DataRow dr = dt.NewRow();
                    for (int i = row.FirstCellNum; i < row.LastCellNum; i++) {
                        ICell cell = row.GetCell(i);
                        if (cell == null) {
                            dr[i] = null;
                        } else {
                            switch (cell.CellType) {
                                case CellType.Blank:
                                    dr[i] = "[null]";
                                    break;
                                case CellType.Boolean:
                                    dr[i] = cell.BooleanCellValue;
                                    break;
                                case CellType.Numeric:
                                    dr[i] = cell.ToString();
                                    break;
                                case CellType.String:
                                    dr[i] = cell.StringCellValue;
                                    break;
                                case CellType.Error:
                                    dr[i] = cell.ErrorCellValue;
                                    break;
                                case CellType.Formula:
                                    try {
                                        dr[i] = cell.NumericCellValue;
                                    } catch {
                                        dr[i] = cell.StringCellValue;
                                    }
                                    break;
                                default:
                                    dr[i] = "=" + cell.CellFormula;
                                    break;
                            }
                        }
                    }
                    dt.Rows.Add(dr);
                    irow++;
                }
            }
            return dt;
        }
    } catch (Exception e){
        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK);
        if (file != null) {
            file.Close();
        }
        return null;
    }
}

 There are several points to note

  • NPOI for different Excel ways of handling different file types, I am currently contacted .xls and .xlsx files, you need to create different classes (see lines 9-12). But it can be unified with IWorkbook to receive class.
  • NPOI read table, the index is from zero (row, column all) of
  • Gets the number of columns approach is to take a line and then get LastCellNum property
  • Column is the code added to the line 23, line 27. Special attention if it is empty, you need to add their own value (line 25), otherwise it will error
  • If the specific extraction column, line 29 may be employed to line 34
  • Line 37 and line 39 shows two ways of adding the line cycle. Special attention, adding columns, when in fact, has read the first line of the original data in the table, so add the line position is actually 1 . That's why the first 40-43 lines of code written.
  • From Excel read row in the data table in two ways: 1) the current line; 2) according to the read index (see line 44)
  • When NPOI read table assigned DataTable , the latter column as a default the first row .

Guess you like

Origin www.cnblogs.com/RicardoIsLearning/p/12115911.html