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的文件,不过其 ...
随机推荐
- Kotlin 基本数据类型
Kotlin 的基本数值类型包括 Byte.Short.Int.Long.Float.Double 等.不同于Java的是,字符不属于数值类型,是一个独立的数据类型. 类型 位宽度 Double 64 ...
- [MySQL]配置多个MySQL服务(Windows)
配置多个MySQL服务 1.复制原解压好的MySQL文件到本目录下,且改名为MySQL2 2.修改MySQL2文件夹中的my.ini 修改my.ini文件中的以下内容,并保存文件: [client] ...
- erlang 笔记(06/03/02)
1 .同时打开的端口数量限制(Open ports) erlang:system_info(port_limit)查询 可以通过环境变量ERL_MAX_PORTS修改,或者配置erlang启动参数(标 ...
- Luffy之购物车页面搭建
前面已经将一些课程加入购物车中,并保存到了后端的redis数据库中,此时做购物车页面时,我们需要将在前端向后端发送请求,用来获取数据数据 购物车页面 1.首先后端要将数据构建好,后端视图函数如下代码: ...
- laravel StartSession中间件的实现原理
1. 打开app\Http\Kernel.php,找到StartSession的位置.这里要说一下,middleware中的中间件是都会被执行的,但执行的顺序我不知道,还需看源码来实现 protect ...
- 『流畅的Python』第14章:可迭代的对象、迭代器和生成器
- openstack详细笔记-nova-glance-swift-cinder-keystone等
一.openstack各大模块 1.openstack总架构图 http://3ms.huawei.com/km/blogs/details/2655265 2.nova 2.0架构图 2.1 nov ...
- Mysql按周,按月,按日,按小时分组统计数据
按周 select DATE_FORMAT(create_time,'%Y%u') weeks,count(caseid) count from tc_case group by weeks; ...
- PAT 1069 The Black Hole of Numbers
1069 The Black Hole of Numbers (20 分) For any 4-digit integer except the ones with all the digits ...
- GIS中的引擎:地图引擎
什么是地图引擎?它和地图软件有什么区别? 引擎一词是英文单词engine的音译,通常指发动机,就是动力输出设备.诸如汽车.轮船.飞机的动力提供的核心设备就是引擎.IT领域中,常听说的有搜索引擎.图形引 ...