zoukankan      html  css  js  c++  java
  • Excel中的数据与DataSet的互换

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Runtime.Remoting.Messaging;
    using Infragistics.Documents.Excel;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;

    namespace Handle.Common
    {
    public static class ExcelHandler
    {
    /// <summary>
    /// Excel exist not only one sheet
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static DataSet ExcelToDataSet(string fileName)
    {
    FileStream filestream;
    IWorkbook workbook = null;
    var ds = new DataSet();
    try
    {
    if (!string.IsNullOrEmpty(fileName))
    {
    filestream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    if (fileName.IndexOf(".xlsx") > 0) // Version 2007
    {
    workbook = new XSSFWorkbook(filestream);
    }
    else if (fileName.IndexOf(".xls") > 0) // Version 2003
    {
    workbook = new HSSFWorkbook(filestream);
    }
    }
    if (null != workbook)
    {
    ISheet sheet = null;
    for (var sheetIndex = 0; sheetIndex < workbook.NumberOfSheets; sheetIndex++)
    {
    sheet = workbook.GetSheetAt(sheetIndex);

    #region Get column name from Excel file

    var dt = new DataTable();
    var titleRow = sheet.GetRow(0);
    if (null != titleRow)
    {
    int columnNums = titleRow.LastCellNum;
    for (int i = titleRow.FirstCellNum; i < columnNums; ++i)
    {
    var cell = titleRow.GetCell(i);
    if (null != cell)
    {
    var col = new DataColumn(cell.StringCellValue.Trim().ToUpper());
    dt.Columns.Add(col);
    }
    }

    #endregion

    #region Get data from Excel file

    var rowCount = sheet.LastRowNum;
    for (var i = 1; i <= rowCount; ++i)
    {
    var row = sheet.GetRow(i);
    if (row == null)
    {
    break;
    }

    var dataRow = dt.NewRow();
    for (int j = row.FirstCellNum; j < columnNums; ++j)
    {
    if (row.GetCell(j) != null)
    {
    dataRow[j] = row.GetCell(j).ToString();
    }
    }
    dt.Rows.Add(dataRow);
    }
    }

    #endregion

    dt.TableName = sheet.SheetName.Trim();
    ds.Tables.Add(dt);
    }
    }
    }
    catch (Exception ex)
    {
    throw ex;
    }
    return ds;
    }

    public static Workbook DataSetToExcel(DataSet ds)
    {
    var workbook = new Workbook();
    if (ds == null || ds.Tables.Count <= 0)
    {
    return workbook;
    }
    foreach (DataTable dt in ds.Tables)
    {
    var rowCount = dt.Rows.Count;
    var columnCount = dt.Columns.Count;
    var sheet = workbook.Worksheets.Add(dt.TableName);
    workbook.CellReferenceMode = CellReferenceMode.R1C1;
    var table = sheet.Tables.Add(string.Format("R1C1:R{0}C{1}", rowCount + 1, columnCount), true,
    workbook.DefaultTableStyle);
    for (var j = 0; j < dt.Columns.Count; j++)
    {
    var columnNameSplit = dt.Columns[j].ColumnName.Trim().Split(' ');
    table.Columns[j].Name = columnNameSplit[columnNameSplit.Length - 1];
    var i = 1;
    foreach (var dataRow in dt.AsEnumerable())
    {
    sheet.Rows[i++].Cells[j].Value = dataRow[j];
    }
    }
    }
    return workbook;
    }

    public static void AddDataTableToExcel(Worksheet workSheet, DataTable dt, int starRowIndex = 0,
    int starColIndex = 0)
    {
    if (dt != null && dt.Rows.Count > 0)
    {
    var rowCount = dt.Rows.Count;
    var columnCount = dt.Columns.Count;
    for (var j = 0; j < dt.Columns.Count; j++)
    {
    var i = 0;
    foreach (var dataRow in dt.AsEnumerable())
    {
    workSheet.Rows[starRowIndex + i++].Cells[starColIndex + j].Value = dataRow[j].ToString();
    }
    }
    }
    }

    public static void ListToExcel(DataTable modeldt, Worksheet workSheet, string columnsName, int starRowIndex = 0,
    int starColIndex = 0)
    {
    DataTableConvert.ChangeDataTableColumnPosition(modeldt, columnsName);
    AddDataTableToExcel(workSheet, modeldt, starRowIndex, starColIndex);
    }

    public static Workbook CustomerLoadWorkBook(string templetefilename, bool isHidden = true)
    {
    var templetePath = Path.Combine(Environment.CurrentDirectory, "ExcelTemplete", templetefilename);
    var templeteWorkbook = Workbook.Load(templetePath);

    //templeteWorkbook.CellReferenceMode = CellReferenceMode.R1C1;
    templeteWorkbook.CellReferenceMode = CellReferenceMode.A1;
    templeteWorkbook.WindowOptions.SelectedWorksheet = templeteWorkbook.Worksheets[1];
    if (isHidden) HiddenOrShowActinResult(templeteWorkbook, true);

    ExcelHandle.WorkbookLocked(templeteWorkbook);

    return templeteWorkbook;
    }
    public static void HiddenOrShowActinResult(Workbook workbook, bool isHidden)
    {
    foreach (var wksheet in workbook.Worksheets)
    {
    if (wksheet.Name.ToUpper() != "INTRODUCTION")
    {
    if (wksheet.Rows[0].Cells[0].Value != null)
    {
    if (wksheet.Rows[0].Cells[0].Value.ToString().ToUpper() == "ACTION" || wksheet.Rows[0].Cells[0].Value.ToString().ToUpper() == "RESULT")
    wksheet.Columns[0].Hidden = isHidden;
    }
    if (wksheet.Rows[0].Cells[1].Value != null)
    {
    if (wksheet.Rows[0].Cells[1].Value.ToString().ToUpper() == "RESULT")
    wksheet.Columns[1].Hidden = isHidden;
    }
    }
    else
    {
    //hidden wksheet
    wksheet.DisplayOptions.Visibility = (isHidden ? WorksheetVisibility.Hidden : WorksheetVisibility.Visible);
    }
    }
    }

    public static void CreatWorksheet<T>(Workbook templeteWorkbook, string templeteSheetName, List<T> modelList,
    string columnsName, int starRowIndex = 0, int starColIndex = 0)
    {
    var workSheet = templeteWorkbook.Worksheets[templeteSheetName];
    workSheet.DisplayOptions.PanesAreFrozen = true;
    workSheet.DisplayOptions.FrozenPaneSettings.FrozenRows = starRowIndex;
    workSheet.DisplayOptions.FrozenPaneSettings.FrozenColumns = starColIndex + 1;
    var modeldt = DataTableConvert.ListToDataTable(modelList);
    ListToExcel(modeldt, workSheet, columnsName, starRowIndex, starColIndex);
    }

    public static void CreatWorksheet<T>(Workbook templeteWorkbook, WorksheetModel wksheetModel, List<T> modelList)
    {
    CreatWorksheet(templeteWorkbook, wksheetModel.SheetName, modelList, wksheetModel.ColumnsName,
    wksheetModel.StarRowIndex, wksheetModel.StarColIndex);
    }

    public static void AddHyperlinkToCell(Workbook templeteWorkbook, string templeteSheetName,
    string hyperlinkSheetName, int starRowIndex = 0, int starColIndex = 0)
    {
    var hyperlink = @"=HYPERLINK(""{0}!R1C1"", ""{1}"")";
    var workSheet = templeteWorkbook.Worksheets[templeteSheetName];
    for (var i = starRowIndex; i < workSheet.Rows.Count(); i++)
    {
    var d = string.Format(hyperlink, hyperlink, workSheet.Rows[i].Cells[starColIndex].Value);
    workSheet.Rows[i].Cells[starColIndex].ApplyFormula(string.Format(hyperlink, hyperlinkSheetName,
    workSheet.Rows[i].Cells[starColIndex].Value));
    }
    }

    public static DataTable ExtractDataTableFromExcel(Workbook workBook, WorksheetModel wksheetModel)
    {
    var workSheet = workBook.Worksheets[wksheetModel.SheetName];
    var dt = new DataTable();
    if (workSheet.Rows.Count() > wksheetModel.StarRowIndex)
    {
    var columnNameArry =
    wksheetModel.ColumnsName.ToLower()
    .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
    .ToList();
    foreach (var clname in columnNameArry)
    {
    dt.Columns.Add(clname, typeof(string));
    }
    for (var i = wksheetModel.StarRowIndex; i < workSheet.Rows.Count(); i++)
    {
    //If not terminated in the value of the first column reads;如果第一列没有值则终止读取
    if (workSheet.Rows[i].Cells[2].Value == null) break;
    var dr = dt.NewRow();
    for (var j = 0; j < columnNameArry.Count; j++)
    {
    dr[j] = workSheet.Rows[i].Cells[wksheetModel.StarColIndex + j].Value == null
    ? ""
    : workSheet.Rows[i].Cells[wksheetModel.StarColIndex + j].Value.ToString();
    }
    dt.Rows.Add(dr);
    }
    }
    return dt;
    }

    public static void WorkbookLocked(Workbook workBook)
    {
    workBook.Protect(false, true);
    foreach (var wksheet in workBook.Worksheets)
    {
    foreach (WorksheetColumn c in wksheet.Columns)
    {
    c.CellFormat.Locked = ExcelDefaultableBoolean.True;
    }
    // wksheet.Protect();
    wksheet.Protect(false, false, false, false, false, false, true, false, false, false, false, true, null);
    }
    }
    public static void WorkbookUnLocked(Workbook workBook)
    {
    foreach (var wksheet in workBook.Worksheets)
    {
    if (wksheet.Name.ToUpper() != "INTRODUCTION")
    {
    wksheet.Unprotect();
    foreach (WorksheetColumn c in wksheet.Columns)
    {
    c.CellFormat.Locked = ExcelDefaultableBoolean.False;
    }
    if (wksheet.Rows[0] != null && wksheet.Rows[0].Cells[0].AssociatedMergedCellsRegion != null)
    {
    if (wksheet.Rows[0].Cells[0].AssociatedMergedCellsRegion != null)
    {
    wksheet.Rows[0].Cells[0].CellFormat.Locked = ExcelDefaultableBoolean.True;
    }
    if (wksheet.Rows[0].Cells[1].AssociatedMergedCellsRegion != null)
    {
    wksheet.Rows[0].Cells[1].CellFormat.Locked = ExcelDefaultableBoolean.True;
    }
    int mergRows = wksheet.Rows[0].Cells[0].AssociatedMergedCellsRegion.LastRow;
    for (int i = 0; i <= mergRows; i++)
    {
    wksheet.Rows[i].CellFormat.Locked = ExcelDefaultableBoolean.True;
    }
    }
    //wksheet.Protect();
    wksheet.Protect(null, true, false, null, null, null, true, null, null, null, true, true, null);
    }
    }
    }
    /// <summary>
    /// disableColIndex start coloums is wksheetModel.starColIndex,起始列为wksheetModel.starColIndex所在列
    /// </summary>
    /// <param name="wksheet"></param>
    /// <param name="wksheetModel"></param>
    /// <param name="rowsCount"></param>
    /// <param name="disableColIndex"></param>
    public static void WorksheetLockedContrl(Workbook workBook, WorksheetModel wksheetModel, int rowsCount,
    params int[] disableColIndex)
    {
    var wksheet = workBook.Worksheets[wksheetModel.SheetName];
    wksheet.Protect(false, false, false, false, false, false, false, false, false, false, false, true, null);
    var cloumsCount = wksheetModel.ColumnsName.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Length;
    var starRowIndex = wksheetModel.StarRowIndex;
    var starColIndex = wksheetModel.StarColIndex;
    for (var i = 0; i < rowsCount; i++)
    {
    for (var j = 0; j < cloumsCount; j++)
    {
    if (!disableColIndex.Contains(j))
    {
    wksheet.Rows[starRowIndex + i].Cells[starColIndex + j].CellFormat.Locked =
    ExcelDefaultableBoolean.False;
    }
    else
    {
    wksheet.Rows[starRowIndex + i].Cells[starColIndex + j].CellFormat.Font.ColorInfo =
    new WorkbookColorInfo(Color.Gray);
    }
    }
    }
    }

    /// <summary>
    /// disableColIndex start coloums is wksheetModel.starColIndex,起始列为wksheetModel.starColIndex所在列
    /// </summary>
    /// <param name="wksheet"></param>
    /// <param name="wksheetModel"></param>
    /// <param name="rowsCount"></param>
    /// <param name="disableColIndex"></param>
    public static void WorksheetLockedContrl(Worksheet wksheet, WorksheetModel wksheetModel, int rowsCount,
    params int[] disableColIndex)
    {
    wksheet.Protect(false, false, false, false, false, false, false, false, false, false, false, true, null);
    var cloumsCount = wksheetModel.ColumnsName.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Length;
    var starRowIndex = wksheetModel.StarRowIndex;
    var starColIndex = wksheetModel.StarColIndex;
    for (var i = 0; i < rowsCount; i++)
    {
    for (var j = 0; j < cloumsCount; j++)
    {
    if (!disableColIndex.Contains(j))
    {
    wksheet.Rows[starRowIndex + i].Cells[starColIndex + j].CellFormat.Locked =
    ExcelDefaultableBoolean.False;
    }
    else
    {
    wksheet.Rows[starRowIndex + i].Cells[starColIndex + j].CellFormat.Font.ColorInfo =
    new WorkbookColorInfo(Color.Gray);
    }
    }
    }
    }

    public static void WorksheetAddActioinResult(Workbook woorkbook, List<ActionResult> arList,
    WorksheetModel worksheetmodel)
    {
    var worksheet = woorkbook.Worksheets[worksheetmodel.SheetName];
    var starRow = worksheetmodel.StarRowIndex;
    for (var i = 0; i < arList.Count; i++)
    {
    worksheet.Rows[starRow + i].Cells[0].Value = arList[i].Action;
    worksheet.Rows[starRow + i].Cells[1].Value = arList[i].Result;
    if (arList[i].Result == ResultEnum.Success.ToString())
    {
    worksheet.Rows[starRow + i].Cells[0].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Black);
    worksheet.Rows[starRow + i].Cells[1].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Black);
    }
    if (arList[i].Result == null) continue;
    if (arList[i].Result.Contains(ResultEnum.Failure.ToString()))
    {
    worksheet.Rows[starRow + i].Cells[0].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Blue);
    worksheet.Rows[starRow + i].Cells[1].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Blue);
    }
    if (arList[i].Result.Contains(ResultEnum.Exception.ToString()))
    {
    worksheet.Rows[starRow + i].Cells[0].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Red);
    worksheet.Rows[starRow + i].Cells[1].CellFormat.Font.ColorInfo = new WorkbookColorInfo(Color.Red);
    }
    }
    }

    /// <summary>
    /// Copying a worksheet Infragistics.Documents.Excel worksheet
    /// </summary>
    /// <param name="workbook"></param>
    /// <param name="worksheet"></param>
    /// <param name="sourceWorksheet"></param>
    public static void CopyWorksheet(Workbook workbook, Worksheet worksheet, Worksheet sourceWorksheet)
    {
    /*外部调用此方法代码 Infragistics 15.1存在bug不能使用 需要使用15.2版本才可调用
    //var dao = new BaseBL();
    //string templetePath = Path.Combine(Environment.CurrentDirectory, "ExcelTemplete", "QTime1.xls");
    //Workbook templeteWorkbook = Workbook.Load(templetePath );
    //templeteWorkbook.SetCurrentFormat(WorkbookFormat.Excel97To2003);
    //Worksheet templeteSheet = templeteWorkbook.Worksheets[0];

    //var qtimelist = dao.QueryEntitiesBySqlCommond<qtime>("select qtimename from fabqtime ").ToList();
    //Workbook workbook = new Workbook(WorkbookFormat.Excel97To2003); //ExcelHandle.DataSetToExcel(DataTableConvert.ListToDataSet(qtimelist));
    //Worksheet sheet = workbook.Worksheets.Add(templeteSheet.Name);
    ////sheet.MoveToIndex(0);
    //CopyWorksheet(workbook, sheet, templeteSheet);
    ////ExportWorkBook = ExcelHandle.DataSetToExcel(DataTableConvert.ListToDataSet(qtimelist));
    //ExportWorkBook = workbook;
    */
    foreach (var sourceColumn in sourceWorksheet.Columns)
    {
    var destinationColumn = worksheet.Columns[sourceColumn.Index];
    destinationColumn.CellFormat.SetFormatting(CreateFormatCopy(workbook, sourceColumn.CellFormat));
    destinationColumn.Width = sourceColumn.Width;
    destinationColumn.Hidden = sourceColumn.Hidden;
    }
    foreach (var sourceRow in sourceWorksheet.Rows)
    {
    var destinationRow = worksheet.Rows[sourceRow.Index];
    destinationRow.CellFormat.SetFormatting(CreateFormatCopy(workbook, sourceRow.CellFormat));
    destinationRow.Height = sourceRow.Height;
    destinationRow.Hidden = sourceRow.Hidden;
    foreach (var sourceCell in sourceRow.Cells)
    {
    var destinationCell = destinationRow.Cells[sourceCell.ColumnIndex];
    destinationCell.CellFormat.SetFormatting(CreateFormatCopy(workbook, sourceCell.CellFormat));
    destinationCell.Value = sourceCell.Value;
    }
    }
    }

    private static IWorksheetCellFormat CreateFormatCopy(Workbook workbook, IWorksheetCellFormat sourceCellFormat)
    {
    var copy = workbook.CreateNewWorksheetCellFormat();
    copy.SetFormatting(sourceCellFormat); //Infragistics 15.1存在bug不能使用
    return copy;
    }

    /// <summary>
    /// Get data from WorkBook and convert to DataSet
    /// </summary>
    /// <param name="workBook">The object that Encapsulated Excel file</param>
    /// <param name="headerIndex">Row number of column name, default value is 1</param>
    /// <param name="startRow">Row number of the first data row, default value is 3</param>
    /// <param name="startColumn">Column number of the first data column, default value is 0</param>
    /// <returns>
    /// DataSet may be contain multiple sheet, every sheet should map to a DataTable except sheet named
    /// "Introduction", DataTable's name same to sheet name
    /// </returns>
    public static DataSet WorkBookConvertToDataSet(Workbook workBook, int headerIndex = 1, int startRow = 3,
    int startColumn = 0)
    {
    string startTime = LoggerHelper.StartEvent();

    if (null == workBook || null == workBook.Worksheets || workBook.Worksheets.Count <= 0 || headerIndex < 0 ||
    startRow <= 0 || startColumn < 0 || headerIndex >= startRow)
    {
    return null;
    }

    var ds = new DataSet();
    try
    {
    foreach (var workSheet in workBook.Worksheets)
    {
    if (null != workSheet && !String.IsNullOrEmpty(workSheet.Name) &&
    !workSheet.Name.ToLower().Equals(CommonConst.EXCELTEMPLATE_FirstSheetName.ToLower())
    /*&& workSheet.Rows.Any() && workSheet.Columns.Any() && workSheet.Rows.Count() > startRow && workSheet.Columns.ToList().Count > startColumn*/)
    {
    var dt = new DataTable();
    dt.TableName = workSheet.Name;

    //Add two columns (Action and Result)
    //var action = workSheet.Rows[0].Cells[CommonConst.EXCELTEMPLATE_ColumnNumber_Action].Value;
    //var result = workSheet.Rows[0].Cells[CommonConst.EXCELTEMPLATE_ColumnNumber_Result].Value;
    //dt.Columns.Add(result == null ? CommonConst.EXCELTEMPLATE_ColumnName_Result : result.ToString());
    int additionalCols = GetStartColumnIndex(workSheet, ref dt);

    var headerColumnCount = workSheet.Rows[headerIndex].Cells.Count();
    var stopColumnIndex = 0;
    for (var n = startColumn + additionalCols; n < headerColumnCount; n++)
    {
    var columnName = workSheet.Rows[headerIndex].Cells[n].Value;
    var val = columnName == null || string.IsNullOrEmpty(columnName.ToString()) ||
    string.IsNullOrEmpty(columnName.ToString().Trim())
    ? string.Empty
    : columnName.ToString().Trim();
    stopColumnIndex = n + 1;
    if (string.IsNullOrEmpty(val))
    {
    stopColumnIndex = n;
    break;
    }
    else if (!dt.Columns.Contains(val))
    {
    dt.Columns.Add(val);
    }
    }
    dt.Columns.Add(CommonConst.EXCELTEMPLATE_RowNumber);

    for (var i = startRow; i < workSheet.Rows.Count(); i++)
    {
    var dr = dt.NewRow();
    for (var j = startColumn; j < stopColumnIndex; j++)
    {
    var cellObj = workSheet.Rows[i].Cells[j];
    var cellValue = cellObj == null ? string.Empty : workSheet.Rows[i].Cells[j].Value;
    dr[j - startColumn] = cellValue == null ? string.Empty : cellValue.ToString();
    }
    dr[CommonConst.EXCELTEMPLATE_RowNumber] = i;
    dt.Rows.Add(dr);
    }
    ds.Tables.Add(dt);
    }
    }

    return ds;
    }
    catch (Exception)
    {
    throw;
    }
    finally
    {
    LoggerHelper.EndEvent(startTime);
    }
    }

    /// <summary>
    /// </summary>
    /// <typeparam name="T">DTO class</typeparam>
    /// <param name="templeteWorkbook">Excel template</param>
    /// <param name="modelList">source data</param>
    /// <param name="sheetName">name of target sheet</param>
    /// <param name="headerIndex">Row number of column name, default value is 1</param>
    /// <param name="startRow">Row number of the first data row, default value is 3</param>
    /// <param name="startColumn">Column number of the first data column, default value is 0</param>
    public static void SetDtoDataToTemplate<T>(ref Workbook templeteWorkbook, List<T> modelList, string sheetName,
    int headerIndex = 1, int startRow = 3, int startColumn = 0)
    {
    if (null == templeteWorkbook || null == modelList || modelList.Count == 0 || string.IsNullOrEmpty(sheetName) ||
    !templeteWorkbook.Worksheets.Exists(sheetName)
    || headerIndex < 0 || startRow <= 0 || startColumn < 0 || headerIndex >= startRow)
    {
    return;
    }

    var sheet = templeteWorkbook.Worksheets[sheetName];
    var headerColumnCount = sheet.Rows[headerIndex].Cells.Count();
    var objInfoDic = XmlDataCache.GetInstance().GetObjectInfoById(sheetName);
    Dictionary<string, string> propertiesDic = null;
    if (null != objInfoDic && null != objInfoDic[CommonConst.KEY_ClassInfo] && objInfoDic[CommonConst.KEY_ClassInfo].Any())
    {
    propertiesDic = objInfoDic[CommonConst.KEY_ClassInfo];
    }
    else
    {
    return;
    }

    DataTable param = new DataTable();
    int additionalCols = GetStartColumnIndex(sheet, ref param);
    if (null != propertiesDic && propertiesDic.Keys.Count >= 0)
    {
    var i = 0;
    foreach (var modelClass in modelList)
    {
    var type = modelClass.GetType();
    var keyColl = propertiesDic.Keys;
    foreach (var key in keyColl)
    {
    if (!String.IsNullOrEmpty(key) && null != propertiesDic[key])
    {
    var property = type.GetProperty(propertiesDic[key]);
    if (null != property)
    {
    var valueObj = property.GetValue(modelClass, null);
    if (null != valueObj && !string.IsNullOrEmpty(valueObj.ToString()))
    {
    for (var n = startColumn + additionalCols; n < headerColumnCount; n++)
    {
    var columnName = sheet.Rows[headerIndex].Cells[n].Value;
    var val = columnName == null ? string.Empty : columnName.ToString();
    if (!string.IsNullOrEmpty(val) &&
    val.Trim().ToUpper().Equals(key.Trim().ToUpper()))
    {
    sheet.Rows[startRow + i].Cells[n].Value = valueObj.ToString();
    break;
    }
    }
    }
    }
    }
    }
    i++;
    }
    }
    }

    public static void SetDtoDataToTemplate<T>(ref Workbook templeteWorkbook, List<T> modelList,
    WorksheetModel sheetmodel)
    {
    SetDtoDataToTemplate(ref templeteWorkbook, modelList, sheetmodel.SheetName, sheetmodel.HeaderIndex,
    sheetmodel.StarRowIndex, sheetmodel.StarColIndex);
    }


    public static void SetDtoDataToTemplateCompareSheet<T>(ref Workbook templeteWorkbook, List<T> modelList,
    WorksheetModel sheetmodel, string sourceSheetname)
    {
    SetDtoDataToTemplateCompareSheet(ref templeteWorkbook, modelList, sheetmodel.SheetName, sourceSheetname, sheetmodel.HeaderIndex,
    sheetmodel.StarRowIndex, sheetmodel.StarColIndex);
    }

    /// <summary>
    /// </summary>
    /// <typeparam name="T">DTO class</typeparam>
    /// <param name="templeteWorkbook">Excel template</param>
    /// <param name="modelList">source data</param>
    /// <param name="sheetName">name of target sheet</param>
    /// <param name="headerIndex">Row number of column name, default value is 1</param>
    /// <param name="startRow">Row number of the first data row, default value is 3</param>
    /// <param name="startColumn">Column number of the first data column, default value is 0</param>
    public static void SetDtoDataToTemplateCompareSheet<T>(ref Workbook templeteWorkbook, List<T> modelList,
    string sheetName, string sourceSheetname,
    int headerIndex = 1, int startRow = 3, int startColumn = 0)
    {
    if (null == templeteWorkbook || null == modelList || modelList.Count == 0 || string.IsNullOrEmpty(sheetName) ||
    !templeteWorkbook.Worksheets.Exists(sheetName)
    || headerIndex < 0 || startRow <= 0 || startColumn < 0 || headerIndex >= startRow)
    {
    return;
    }

    var sheet = templeteWorkbook.Worksheets[sheetName];
    var headerColumnCount = sheet.Rows[headerIndex].Cells.Count();
    var objInfoDic = XmlDataCache.GetInstance().GetObjectInfoById(sourceSheetname);
    Dictionary<string, string> propertiesDic = null;
    if (null != objInfoDic && null != objInfoDic[CommonConst.KEY_ClassInfo] && objInfoDic[CommonConst.KEY_ClassInfo].Any())
    {
    propertiesDic = objInfoDic[CommonConst.KEY_ClassInfo];
    }
    else
    {
    return;
    }

    DataTable param = new DataTable();
    int additionalCols = GetStartColumnIndex(sheet, ref param);
    if (null != propertiesDic && propertiesDic.Keys.Count >= 0)
    {
    var i = 0;
    foreach (var modelClass in modelList)
    {
    var type = modelClass.GetType();
    var keyColl = propertiesDic.Keys;
    foreach (var key in keyColl)
    {
    if (!String.IsNullOrEmpty(key) && null != propertiesDic[key])
    {
    var property = type.GetProperty(propertiesDic[key]);
    if (null != property)
    {
    var valueObj = property.GetValue(modelClass, null);
    if (null != valueObj && !string.IsNullOrEmpty(valueObj.ToString()))
    {
    for (var n = startColumn + additionalCols; n < headerColumnCount; n++)
    {
    var columnName = sheet.Rows[headerIndex].Cells[n].Value;
    var val = columnName == null ? string.Empty : columnName.ToString();
    if (!string.IsNullOrEmpty(val) &&
    val.Trim().ToUpper().Equals(key.Trim().ToUpper()))
    {
    sheet.Rows[startRow + i].Cells[n].Value = valueObj.ToString();
    break;
    }
    }
    }
    }
    }
    }
    i++;
    }
    }
    }

    private static int GetStartColumnIndex(Worksheet sheet, ref DataTable dataTable)
    {
    int additionalCols = 0;
    for (int i = 0; i < 2; i++)
    {
    var columnVal = sheet.Rows[0].Cells[i].Value;
    if (null != columnVal && !string.IsNullOrEmpty(columnVal.ToString()) && CommonConst.EXCELTEMPLATE_ColumnName_Action.Equals(columnVal.ToString()))
    {
    additionalCols++;
    if (null != dataTable)
    {
    dataTable.Columns.Add(columnVal.ToString());
    }
    }
    if (null != columnVal && !string.IsNullOrEmpty(columnVal.ToString()) && CommonConst.EXCELTEMPLATE_ColumnName_Result.Equals(columnVal.ToString()))
    {
    additionalCols++;
    if (null != dataTable)
    {
    dataTable.Columns.Add(columnVal.ToString());
    }
    }
    }

    return additionalCols;
    }

    }
    }

  • 相关阅读:
    linux下使用kermi续
    关于vhdl中integer消耗资源的一些讨论
    linux时间编程
    Linux下C编程文件编程
    C语言I博客作业04
    C语言I博客作业02
    C语言I博客作业02
    第一周作业
    php 面向对象
    php 面向对象封装和继承
  • 原文地址:https://www.cnblogs.com/zunzunQ/p/7580787.html
Copyright © 2011-2022 走看看