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;
}
}
}
Excel中的数据与DataSet的互换的更多相关文章
- 读取Excel中的数据到DataSet
读取Excel中的数据到DataSet 1.引用命名空间 using System.Data.OleDb; 2.输入Excel文件,输出DataSet public DataSet ExecleDs( ...
- 使用OpenXml把Excel中的数据导出到DataSet中
public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </sum ...
- C# Unity游戏开发——Excel中的数据是如何到游戏中的 (二)
本帖是延续的:C# Unity游戏开发——Excel中的数据是如何到游戏中的 (一) 上个帖子主要是讲了如何读取Excel,本帖主要是讲述读取的Excel数据是如何序列化成二进制的,考虑到现在在手游中 ...
- NOPI读取模板导出(Excel中追加数据)
在Controller里,我们定义一个FileResult的Action,返回值是一个文件形式被浏览器下载下来. [HttpGet] public FileResult ExportProductLi ...
- 使用Python将Excel中的数据导入到MySQL
使用Python将Excel中的数据导入到MySQL 工具 Python 2.7 xlrd MySQLdb 安装 Python 对于不同的系统安装方式不同,Windows平台有exe安装包,Ubunt ...
- Java利用POI导入导出Excel中的数据
首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...
- sql 读取excel中的数据
select 列名 as 字段名 from openBowSet('MSDASQL.1','driver=Microsoft Excel Driver(*.xls);dbq=文件存放地址','sele ...
- excel中的数据导入oracle方法
SQL_loader批量上传数据 1. 注释 在工作中,很多时候会遇到如下情况:需要将excel中的数据批量上传到ORACLE表中.如果是小数据量,如几十条至几百条,那么用plsql dev工具 ...
- C# Unity游戏开发——Excel中的数据是如何到游戏中的 (三)
本帖是延续的:C# Unity游戏开发——Excel中的数据是如何到游戏中的 (二) 前几天有点事情所以没有继续更新,今天我们接着说.上个帖子中我们看到已经把Excel数据生成了.bin的文件,不过其 ...
随机推荐
- Linux 查看进程之PS命令
要对进程进行检测和控制,首先必须要了解当前进程的情况,也就是需要查看当前进程运行状态.Linux 系统中 我们可以使用 ps 命令查看进程. ps 命令介绍 ps(process stat ...
- WebApi 运行原理
1.当请求过来时,首先经过Global 下面的Application_start()方法,在这个方法中注册了WebApiConfig.Register 2.WebApiConfig.Register把 ...
- leecode第一百四十六题(LRU缓存机制)
class LRUCache { private: unordered_map<int, list<pair<int,int>>::iterator> _m; // ...
- echarts的axisLabel的文字内容过长的解决办法
通过查找资料学习,我总结了四种解决的办法,不一定是最好的,但是希望能够帮助到需要的童鞋,同时如果大家有什么更好的方法欢迎指导. 方法一:这种方法就是将文本内容转换为字符串数组,然后再按需求换行,需要每 ...
- 2018 ACM-ICPC, Syrian Collegiate Programming Contest
2018 ACM-ICPC, Syrian Collegiate Programming Contest A Hello SCPC 2018! 水题 B Binary Hamming 水题 C Por ...
- fast-route的使用
<?php require 'vendor/autoload.php'; // 通过 FastRoute\simpleDispatcher() 方法定义路由,第一个参数必须是 FastRoute ...
- git创建分支提交到远程分支步骤
git创建分支提交到远程分支步骤 step1,在本地新建分支() git branch newbranch step2:把本地分支push到远程 git push origin newbranch s ...
- VUE + vue-cli + webpack 创建新项目
首先记录一下命令. 这是一个睿智新手的笔记. p.s.这是配置好环境以后的命令. ----------------------------------------------- $ npm insta ...
- linux下无root 安装activepython到指定目录
linux下无root 安装activepython 1.下载ActivePython-2.7.8.10-linux-x86_64.tar.gz 包 2.进入非root用户,如bdc用户,解压 [bd ...
- Python中的lambda的简单介绍
在学习python的过程中,lambda的语法经常出现,现在将它整理一下,以备日后查看. 1.lambda是什么? 举个例子如下: func=lambda x:x+1 print(func(1)) p ...