C#導入Excel

public static List importExecl() 
        {
            List<ImportModel> list = new List<ImportModel>();
            ImportModel model = null;
            try
            {
                BParseExcel parseExcel = null;
                OpenFileDialog ofDlg = new OpenFileDialog();
                ofDlg.Filter = "所有文件 (*.*)|*.*|Excel (*.xls)|*.xls";
                ofDlg.Multiselect = false;
                //System.Windows.Forms.DialogResult dRet = ofDlg.ShowDialog();
                if (ofDlg.ShowDialog() == true)
                {
                    string str_end = ofDlg.FileName.Substring(ofDlg.FileName.LastIndexOf(".") + 1);
                    if (str_end.Equals("xls"))
                    {
                        parseExcel = new BParseExcel(ofDlg.FileName);
                        //parseExcel.setReadSheet("測試");
                        //申請人
                        //if (!IsWu(parseExcel.readCell(1, 1).Trim()))
                        //{
                        for (int i = 0; i < parseExcel.getRows(); i++)
                        {
                            model = new ImportModel();
                            for (int j = 0; j < parseExcel.getCols(i); j++)
                            {
                                string str = parseExcel.readCell(i, j).Trim();
                                //MessageBox.Show(jsjdm);
                                if (j == 0)
                                {
                                    model.jsjdm = str;
                                }
                                else
                                {
                                    model.ajly = str;
                                }
                            }
                            list.Add(model);
                        }
                        //第六行第四列
                        // string jsjdm = parseExcel.readCell(5, 3).Trim();
                        //string tt = jsjdm;
                        //}
                    }
                    else
                    {
                        CMessageBox.ShowWarningMessage("你選擇的文件類型不對,請重新選擇(.xls)!");
                    }
                }
            }
            catch (ExcelException ex)
            {
                CMessageBox.ShowInfoMessage(ex.Message);
            }


            return list;

        }




public class BParseExcel
{
private HSSFWorkbook _workbook = null;


public HSSFWorkbook Workbook
{
get { return _workbook; }
set { _workbook = value; }
}


private HSSFSheet _curSheet = null;


public HSSFSheet CurSheet
{
get { return _curSheet; }
set { _curSheet = value; }
}




#region 構造方法
private BParseExcel()
{
}
/// <summary>
/// 載入Excel
/// 暫支持xls格式的
/// </summary>
/// <param name="fileName"></param>
public BParseExcel(string fileName)
{

try
{
string str_end = fileName.Substring(fileName.LastIndexOf(".") + 1);


FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
Workbook = new HSSFWorkbook(stream);
CurSheet = (HSSFSheet)Workbook.GetSheetAt(0);
stream.Close();
}
catch (Exception)
{
throw new ExcelException("載入Excel異常,注意請不要打開需要載入的表格!");
}


}
        /// <summary>
        /// 獲取單Excel中的總行數
        /// </summary>
        /// <param name="fileName"></param>
        public int getRows() 
        {
            return CurSheet.PhysicalNumberOfRows;
        }


        public int getCols(int row)
        {
            return CurSheet.GetRow(row).PhysicalNumberOfCells;
        }


/// <summary>
/// 載入Excel
/// 暫支持xls格式的
/// </summary>
/// <param name="fileName"></param>
public BParseExcel(string fileName, string sheetName)
{
try
{
string str_end = fileName.Substring(fileName.LastIndexOf(".") + 1);
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
Workbook = new HSSFWorkbook(stream);
CurSheet = (HSSFSheet)Workbook.GetSheet(sheetName);
stream.Close();
}
catch (Exception)
{
throw new ExcelException("載入Excel異常,注意請不要打開需要載入的表格!");
}
}
#endregion
/// <summary>
/// 設置要讀取的sheet表格
/// </summary>
/// <param name="sheetName">表格名</param>
/// <returns></returns>
public void setReadSheet(string sheetName)
{
CurSheet=(HSSFSheet)Workbook.GetSheet(sheetName);
}
/// <summary>
/// readCell 
/// </summary>
/// <param name="curSheet"></param>
/// <param name="x">行</param>
/// <param name="y">列</param>
/// <returns></returns>
public string readCell(int row, int col)
{


string value = string.Empty;
value = "";
int c = col;// 列
int r = row;// 行
try
{
int sheetRows = CurSheet.PhysicalNumberOfRows;

int sheetCells = CurSheet.GetRow(row).PhysicalNumberOfCells;
if ((c < sheetCells) && (r < sheetRows))
{
// 得到工作表(c,r)的單元格
HSSFCell cell = (HSSFCell)CurSheet.GetRow(r).GetCell(c);
// getContents()將Cell中的字符轉爲字符串
value = getCellValue(cell);
//判斷是否是合併的單元格
if (cell.IsMergedCell)
{
// 如果是合併的單元格則取左上角的值
value = GetValueMergedInfo(CurSheet, r, c);
}
}
else
{
value = "";
Console.WriteLine("Cell is null");
}
}
catch (Exception)
{
// TODO 自動生成 catch 塊
throw new ExcelException("獲取單元格的值發生異常!");
}
return value;
}


/// <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">此單元格是否被某個行合併包含在內。如果被包含在內,不輸出 </param> 
/// <returns></returns> 
private  string GetValueMergedInfo(HSSFSheet sheet, int rowIndex, int colIndex)
{
string cell_str = string.Empty;
int regionsCuont = sheet.NumMergedRegions;
CellRangeAddress region;
for (int i = 0; i < regionsCuont; i++)
{
region = sheet.GetMergedRegion(i);
if (region.FirstRow <= rowIndex && region.FirstColumn <= colIndex &&
region.LastRow >= rowIndex && region.LastColumn >= colIndex)
{
  HSSFCell cell=(HSSFCell)sheet.GetRow(region.FirstRow).GetCell(region.FirstColumn);
  cell_str = this.getCellValue(cell);
                       break;
}
}

return cell_str;
}

/// <summary>
/// 根據類型獲取數據
/// 目前只處理日期類型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private string getCellValue(HSSFCell cell){
string cellValue = string.Empty;


if (cell.CellType == CellType.NUMERIC)
{
short format = cell.CellStyle.DataFormat;
/**
* 一下內容摘自網上  具體沒有驗證 如果用時出現問題請及時溝通

*Excel中的日期格式在解析爲DataTable時會依格式不同解析爲不同的值,因爲所有的日期格式都可以通過下面DataFormat來判斷,
*excel2013,測試結果如下:*時分(HH:mm) - 20,時間(HH:mm:ss) - 21,日期時間(yyyy-MM-dd HH:mm:ss) - 22,
*年月(yyyy-MM) - 17,年月日(yyyy-MM-dd)-14,yyyy年m月-------57,月日(MM-dd) - 58,
*yyyy年m月d日---31,h時mm分  -------32
**/
if (format == 14 || format == 31 || format == 57 || format == 58)
{
DateTime date = cell.DateCellValue;
cellValue = date.ToString("yyy-MM-dd");
}
else
{
cellValue = cell.ToString();
}
}
else {
cellValue = cell.ToString();
}
return cellValue;


}



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章