/******************************
* 说明:导出Excel窗口,用于重置数据
* 创建人:龚宇超
* 创建日期:2017-11-14
* 修改人:
* 修改日期:
* 修改备注:
* 版本:1.0.0.0
******************************/
using DevExpress.Utils;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using Lskj.Business;
using Lskj.Control.Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Lskj.Control
{
///
/// 导出Excel窗口,用于重置数据
///
public partial class FrmExport : Form
{
///
/// 临时导出表无法执行原表的自定义汇总逻辑,保存原表已经计算完成的总计值。
///
private readonly Dictionary _exportCustomSummaryValues = new Dictionary(StringComparer.OrdinalIgnoreCase);
public FrmExport()
{
InitializeComponent();
gridView1.Appearance.HeaderPanel.Font = new Font("宋体", 9);
gridView1.Appearance.HeaderPanel.TextOptions.HAlignment = HorzAlignment.Center;
gridView1.Appearance.Preview.Font = new Font("宋体", 9);
gridView1.Appearance.Row.Font = new Font("宋体", 9);
gridView1.OptionsView.RowAutoHeight = true;
gridView1.RowCellStyle += new RowCellStyleEventHandler(OnGridViewRowCellStyle);
gridView1.CustomSummaryCalculate += OnExportCustomSummaryCalculate;
Lskj.Control.Model.AutoSizeChange.ControllInitializeSize(this);
}
///
/// 将原表已经计算完成的自定义总计回填到临时导出表。
///
private void OnExportCustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
{
if (!e.IsTotalSummary || e.SummaryProcess != DevExpress.Data.CustomSummaryProcess.Finalize)
{
return;
}
GridSummaryItem summaryItem = e.Item as GridSummaryItem;
object summaryValue;
if (summaryItem != null && !string.IsNullOrEmpty(summaryItem.FieldName) &&
_exportCustomSummaryValues.TryGetValue(summaryItem.FieldName, out summaryValue))
{
e.TotalValue = summaryValue;
e.TotalValueReady = true;
}
}
///
/// 百分率自定义汇总在原表中可能已经格式化为字符串,导出前还原为数值。
///
private static object GetExportSummaryValue(GridColumn column, GridSummaryItem summaryItem)
{
object summaryValue = summaryItem.SummaryValue;
string valueText = summaryValue as string;
string summaryFormat = summaryItem.DisplayFormat ?? string.Empty;
string columnFormat = column == null ? string.Empty : column.DisplayFormat.FormatString;
if (string.IsNullOrWhiteSpace(valueText) ||
(!summaryFormat.Contains("%") && !columnFormat.Contains("%")))
{
return summaryValue;
}
string percentSymbol = CultureInfo.CurrentCulture.NumberFormat.PercentSymbol;
string numericText = valueText.Replace(percentSymbol, string.Empty).Replace("%", string.Empty).Trim();
decimal percentageValue;
if (decimal.TryParse(numericText, NumberStyles.Any, CultureInfo.CurrentCulture, out percentageValue) ||
decimal.TryParse(numericText, NumberStyles.Any, CultureInfo.InvariantCulture, out percentageValue))
{
return percentageValue / 100m;
}
return summaryValue;
}
///
/// DataTable转换成Excel文档流(导出数据量超出65535条,分sheet)
///
///
///
public static MemoryStream ExportDataTableToExcel(DataTable sourceTable)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
int dtRowsCount = sourceTable.Rows.Count;
int SheetCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(dtRowsCount) / 65536));
int SheetNum = 1;
int rowIndex = 1;
int tempIndex = 1; //标示
ISheet sheet = workbook.CreateSheet("sheet1" + SheetNum);
for (int i = 0; i < dtRowsCount; i++)
{
if (i == 0 || tempIndex == 1)
{
IRow headerRow = sheet.CreateRow(0);
foreach (DataColumn column in sourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(tempIndex);
foreach (DataColumn column in sourceTable.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(sourceTable.Rows[i][column].ToString());
}
if (tempIndex == 65535)
{
SheetNum++;
sheet = workbook.CreateSheet("sheet" + SheetNum);//
tempIndex = 0;
}
rowIndex++;
tempIndex++;
//AutoSizeColumns(sheet);
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
workbook = null;
return ms;
}
///
/// 说明:复制为新表格
/// 创建人:龚宇超
/// 创建日期:2017-11-14
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// The control.
/// GridControl.
public BandedGridControlEx ReplaceBitColumn(BandedGridControlEx bandGridControlEx, bool IsCustomColumn = false)
{
_exportCustomSummaryValues.Clear();
bool hasBoolean = false;
BandedGridView gridView = bandGridControlEx.GridView as BandedGridView;
BandedGridControlEx NewBandedGridControlEx = new BandedGridControlEx();
BandedGridView gridView2 = NewBandedGridControlEx.GridView as BandedGridView;
gridView2.CustomSummaryCalculate += OnExportCustomSummaryCalculate;
gridView2.Columns.Clear();//默认有2个列
List boolList = new List();
List datetimeList = new List();
List visibleList = new List();
Dictionary dictionary = new Dictionary();
List StoreValueList = new List();
InitializeValueGrid(gridView);
foreach (GridColumn col in gridView.Columns)
{
if ((col.ColumnEdit != null && col.ColumnEdit.GetType() == typeof(RepositoryItemCheckEdit)) ||
(col.ColumnType != null && col.ColumnType.Name.ToLower() == "boolean"))
{
boolList.Add(col.FieldName);
hasBoolean = true;
}
if ((col.ColumnType != null && col.ColumnType.Name.ToLower() == "datetime"))
{
datetimeList.Add(col.FieldName);
hasBoolean = true;
}
GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && (model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabSelectReturnId || (model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText) || model.FieldType == ControlType.LabModuleAddRowsID))
{
StoreValueList.Add(col.FieldName);
hasBoolean = true;
}
}
if (hasBoolean || IsCustomColumn)
{
//赋值表格头
foreach (GridBand Band in gridView.Bands)
{
NewBandedGridControlEx.BandedView.Bands.AddBand(Band.Caption);
}
// 复制列
foreach (BandedGridColumn col in gridView.Columns)
{
GridColumnModel gridModel = col.Tag as GridColumnModel;
if (col.Visible)
{
BandedGridColumn newCol = new BandedGridColumn();
newCol.Tag = col.Tag;
newCol.Caption = col.Caption;
newCol.OptionsColumn.AllowMerge = col.OptionsColumn.AllowMerge;
newCol.FieldName = col.FieldName;
newCol.Name = col.Name;
newCol.VisibleIndex = col.VisibleIndex;
newCol.Width = col.Width;
newCol.OptionsColumn.AllowEdit = col.OptionsColumn.AllowEdit;
newCol.ColumnEdit = boolList.Contains(col.FieldName) || datetimeList.Contains(col.FieldName) ? null : col.ColumnEdit;
newCol.DisplayFormat.FormatType = col.DisplayFormat.FormatType;
newCol.DisplayFormat.FormatString = col.DisplayFormat.FormatString;
//多表头默认都有1级标题(默认有空白表头)
if (col.OwnerBand != null)
{
GridBand gridBand = NewBandedGridControlEx.BandedView.Bands.Cast().FirstOrDefault(x => x.Caption == col.OwnerBand.Caption);
gridBand.Columns.Add(newCol);
}
else
{
GridBand gridBand = NewBandedGridControlEx.BandedView.Bands.Cast().FirstOrDefault(x => x.Caption == "");
gridBand.Columns.Add(newCol);
}
visibleList.Add(col.FieldName);
if (gridModel != null && !dictionary.ContainsKey(col.FieldName))
{
dictionary.Add(col.FieldName, gridModel.FieldType);
}
}
}
DataTable sourceTable = gridView.GetGridViewFilteredAndSortedDataToDataTable();
//DataTable sourceTable = (gridView.DataSource as DataView).Table.Select(gridView.RowFilter).CopyToDataTable();
DataTable dtTable = new DataTable();
// 复制DataTable列
foreach (DataColumn col in sourceTable.Columns)
{
if (visibleList.Contains(col.ColumnName))
{
DataColumn newCol = new DataColumn();
newCol.ColumnName = col.ColumnName;
newCol.Caption = col.Caption;
newCol.DataType = boolList.Contains(col.ColumnName) || col.DataType == typeof(DateTime) ? typeof(String) : col.DataType;
dtTable.Columns.Add(newCol);
}
}
// 复制DataTable行
foreach (DataRow row in sourceTable.Rows)
{
DataRow newRow = dtTable.NewRow();
foreach (DataColumn col in sourceTable.Columns)
{
if (visibleList.Contains(col.ColumnName))
{
if (boolList.Contains(col.ColumnName))
{
newRow[col.ColumnName] = row[col.ColumnName] + "" == "0" || (row[col.ColumnName] + "").ToLower() == "false" ? "否" : "是";
}
if (datetimeList.Contains(col.ColumnName))
{
if (row[col.ColumnName] != DBNull.Value)
{
DateTime newTime = (DateTime)row[col.ColumnName];
if (!dictionary.Keys.Contains(col.ColumnName))
{
newRow[col.ColumnName] = newTime.GetDateTimeFormats('g')[0];
}
else
{
switch (dictionary[col.ColumnName])
{
//case "yyyy年MM月DD日":
// newRow[col.ColumnName] = newTime.ToLongDateString();
// break;
case (int)ControlType.LabDateTimeShort:
case (int)ControlType.LabCheckDateTimeShort:
newRow[col.ColumnName] = newTime.GetDateTimeFormats('g')[0];
break;
//case "yyyyMMdd":
// newRow[col.ColumnName] = newTime.ToShortDateString().Replace("-", "");
// break;
case (int)ControlType.LabDate:
case (int)ControlType.LabCheckDateEx:
newRow[col.ColumnName] = newTime.ToShortDateString();
break;
case (int)ControlType.LabTime:
case (int)ControlType.LabCheckTime:
newRow[col.ColumnName] = newTime.ToLongTimeString();
break;
case (int)ControlType.LabShortTime:
case (int)ControlType.LabCheckShortTime:
newRow[col.ColumnName] = newTime.ToShortTimeString();
break;
case (int)ControlType.LabDateTime:
case (int)ControlType.LabCheckDateTimeEx:
newRow[col.ColumnName] = newTime;
break;
}
}
}
}
else if (StoreValueList.Contains(col.ColumnName))
{
string fieldValue = string.Empty;
GridColumn gridColumn = gridView.Columns[col.ColumnName];
if (gridColumn.Tag is GridColumnModel)
{
GridColumnModel model = gridColumn.Tag as GridColumnModel;
if ((model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew ||
model.FieldType == ControlType.LabMultiSelectValueParam) && row[col.ColumnName].ToString().Contains(","))
{
string[] cellText = row[col.ColumnName].ToString().Split(',');
foreach (string cellValue in cellText)
{
fieldValue += GetValueByImportText(model, cellValue, false) + ',';
}
fieldValue = fieldValue.TrimEnd(',');
newRow[col.ColumnName] = fieldValue;
}
else
{
fieldValue = GetValueByImportText(model, row[col.ColumnName] + "" + "", false);
newRow[col.ColumnName] = fieldValue;
}
}
}
else
{
if (string.IsNullOrEmpty(row[col.ColumnName] + "") &&
(col.DataType == typeof(Int16) ||
col.DataType == typeof(Int32) ||
col.DataType == typeof(Int64) ||
col.DataType == typeof(Decimal) ||
col.DataType == typeof(Double)))
{
newRow[col.ColumnName] = 0;
}
else
if (col.DataType == typeof(Byte[]))
{
newRow[col.ColumnName] = row[col.ColumnName] != DBNull.Value ? (Byte[])row[col.ColumnName] : null;
}
else
{
newRow[col.ColumnName] = row[col.ColumnName] + "";
}
}
//处理统计
DataColumn dcIsSum = sourceTable.Columns["isSum"];
if (dcIsSum != null && !String.IsNullOrEmpty(row["isSum"] + ""))
{
int isSum = Convert.ToInt32(row["isSum"]);
int fieldType = Convert.ToInt32(row["fieldsqlTag"]);
string dataFormat = row["DataFormat"] + "";
GridColumn gridColumn = gridView2.Columns[col.ColumnName];
// 格式化数字
if (fieldType == ControlType.LabTextInt || fieldType == ControlType.LabCalcText)
{
gridColumn.DisplayFormat.FormatType = FormatType.Numeric;
gridColumn.DisplayFormat.FormatString = dataFormat;
}
if (isSum == 1)
{
gridView2.OptionsView.ShowFooter = true;
if ((row["calcExpr"] + "").IndexOf("/{") == -1)
{
gridColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), "{0:" + dataFormat + "}") });
if (SystemInfo.Instance.GroupSpecialMode)
{
gridView2.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), gridColumn, "{0:" + dataFormat + "}"));
gridView2.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
gridView2.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), null, "{0:" + dataFormat + "}") });
}
}
else
{
gridColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), "{0:" + dataFormat + "}") });
if (SystemInfo.Instance.GroupSpecialMode)
{
gridView2.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), gridColumn, "{0:" + dataFormat + "}"));
gridView2.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
gridView2.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), null, "{0:" + dataFormat + "}") });
}
}
}
}
}
}
dtTable.Rows.Add(newRow);
}
if (gridView.Columns.Count > 0)
{
GridColumn firstColumn = gridView2.Columns[0];
if (firstColumn != null)
{
gridView2.OptionsView.ShowFooter = true;
firstColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count, firstColumn.FieldName.ToString(), "合计: {0:#,###}行") });
if (SystemInfo.Instance.GroupSpecialMode)
{
//gridView2.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, firstColumn.FieldName.ToString(), firstColumn, "合计: {0:#,###}行"));
gridView2.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
gridView2.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, firstColumn.FieldName.ToString(), null, "合计: {0:#,###}行") });
}
//底部汇总是否导出
if (SystemInfo.Instance.ExportSummary)
{
gridView.UpdateTotalSummary();
for (int i = 1; i < gridView2.Columns.Count; i++)
{
string columnName = gridView2.Columns[i].FieldName;
if (gridView.Columns[columnName] == null) continue;
GridSummaryItem gsi = gridView.Columns[columnName].SummaryItem;
if (gsi.SummaryType != DevExpress.Data.SummaryItemType.None) //gsi.SummaryValue!=null&& !string.IsNullOrEmpty(gsi.SummaryValue.ToString())
{
if (gsi.SummaryType == DevExpress.Data.SummaryItemType.Custom)
{
_exportCustomSummaryValues[columnName] = GetExportSummaryValue(gridView.Columns[columnName], gsi);
}
gridView2.Columns[i].Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(gsi.SummaryType, gridView2.Columns[i].FieldName.ToString(), gsi.DisplayFormat) });
if (SystemInfo.Instance.GroupSpecialMode)
{
gridView2.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(gsi.SummaryType, gridView2.Columns[i].FieldName.ToString(), gridView2.Columns[i], gsi.DisplayFormat));
gridView2.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
gridView2.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(gsi.SummaryType, gridView2.Columns[i].FieldName.ToString(), null, gsi.DisplayFormat) });
}
}
}
}
}
}
NewBandedGridControlEx.gridControl.DataSource = dtTable;
return NewBandedGridControlEx;
}
else
{
return bandGridControlEx;
}
}
///
/// 说明:复制为新表格
/// 创建人:龚宇超
/// 创建日期:2017-11-14
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// The control.
/// GridControl.
public GridControl ReplaceBitColumn(GridControl control, bool IsCustomColumn = false)
{
GridView gridView = control.FocusedView as GridView;
_exportCustomSummaryValues.Clear();
bool hasBoolean = false;
List boolList = new List();
List datetimeList = new List();
List decimalList = new List();
List visibleList = new List();
Dictionary dictionary = new Dictionary();
GridColumnReadOnlyCollection grouping = gridView.GroupedColumns;//分组信息
List StoreValueList = new List();
InitializeValueGrid(gridView);
foreach (GridColumn col in gridView.Columns)
{
if ((col.ColumnEdit != null && col.ColumnEdit.GetType() == typeof(RepositoryItemCheckEdit)) ||
(col.ColumnType != null && col.ColumnType.Name.ToLower() == "boolean"))
{
boolList.Add(col.FieldName);
hasBoolean = true;
}
if ((col.ColumnType != null && col.ColumnType.Name.ToLower() == "datetime"))
{
datetimeList.Add(col.FieldName);
hasBoolean = true;
}
if (col.DisplayFormat.FormatString.Contains(';') && col.DisplayFormat.FormatString.Split(';').Length == 3)
{
decimalList.Add(col.FieldName);
hasBoolean = true;
}
GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && (model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew || model.FieldType == ControlType.LabTreeLookValue || model.FieldType == ControlType.LabMultiSelectValueParam || model.FieldType == ControlType.LabSelectReturnId || (model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText) || model.FieldType == ControlType.LabModuleAddRowsID))
{
StoreValueList.Add(col.FieldName);
hasBoolean = true;
}
}
if (hasBoolean || IsCustomColumn)
{
// 复制列
foreach (GridColumn col in gridView.Columns)
{
GridColumnModel gridModel = col.Tag as GridColumnModel;
if (col.Visible && !col.FieldName.Equals("RightMenuBtnEdit"))
{
GridColumn newCol = new GridColumn();
newCol.Tag = col.Tag;
newCol.Caption = col.Caption;
newCol.OptionsColumn.AllowMerge = col.OptionsColumn.AllowMerge;
newCol.FieldName = col.FieldName;
newCol.Name = col.Name;
newCol.VisibleIndex = col.VisibleIndex;
newCol.Width = col.Width;
newCol.Width = 100;
newCol.OptionsColumn.AllowEdit = col.OptionsColumn.AllowEdit;
newCol.ColumnEdit = boolList.Contains(col.FieldName) || datetimeList.Contains(col.FieldName) ? null : col.ColumnEdit;
newCol.DisplayFormat.FormatType = col.DisplayFormat.FormatType;
newCol.DisplayFormat.FormatString = col.DisplayFormat.FormatString;
this.gridView1.Columns.Add(newCol);
visibleList.Add(col.FieldName);
if (gridModel != null && !dictionary.ContainsKey(col.FieldName))
{
dictionary.Add(col.FieldName, gridModel.FieldType);
}
}
}
DataTable sourceTable = gridView.GetGridViewFilteredAndSortedDataToDataTable();
//DataTable sourceTable = (gridView.DataSource as DataView).Table.Select(gridView.RowFilter).CopyToDataTable();
if (grouping.Count > 0)
{
sourceTable = gridView.GetFilteredAndSortedDataTable();//获取数据表
}
DataTable dtTable = new DataTable();
// 复制DataTable列
foreach (DataColumn col in sourceTable.Columns)
{
if (visibleList.Contains(col.ColumnName))
{
DataColumn newCol = new DataColumn();
newCol.ColumnName = col.ColumnName;
newCol.Caption = col.Caption;
newCol.DataType = boolList.Contains(col.ColumnName) || col.DataType == typeof(DateTime) ? typeof(String) : col.DataType;
GridColumn gridColumn = this.gridView1.Columns[col.ColumnName];
if (decimalList.Contains(col.ColumnName))
{
newCol.DataType = typeof(String);
}
if (datetimeList.Contains(col.ColumnName))
{
newCol.DataType = typeof(DateTime);
//if (dictionary.ContainsKey(col.ColumnName) && (dictionary[col.ColumnName] == (int)ControlType.LabDateTime || dictionary[col.ColumnName] == (int)ControlType.LabCheckDateTimeEx))
//{
// newCol.DataType = typeof(String);//年月日时分秒格式转成String类型。excel表格中时间格式没有这种类型(yyyy-MM-dd HH:mm:ss)
//}
}
if (StoreValueList.Contains(col.ColumnName))
{
newCol.DataType = typeof(String);
}
dtTable.Columns.Add(newCol);
}
}
// 复制DataTable行
foreach (DataRow row in sourceTable.Rows)
{
DataRow newRow = dtTable.NewRow();
foreach (DataColumn col in sourceTable.Columns)
{
if (visibleList.Contains(col.ColumnName))
{
if (boolList.Contains(col.ColumnName))
{
newRow[col.ColumnName] = row[col.ColumnName] + "" == "0" || (row[col.ColumnName] + "").ToLower() == "false" ? "否" : "是";
}
if (datetimeList.Contains(col.ColumnName))
{
if (row[col.ColumnName] != DBNull.Value)
{
DateTime newTime = (DateTime)row[col.ColumnName];
if (!dictionary.Keys.Contains(col.ColumnName))
{
newRow[col.ColumnName] = newTime.GetDateTimeFormats('g')[0];
}
else
{
switch (dictionary[col.ColumnName])
{
//case "yyyy年MM月DD日":
// newRow[col.ColumnName] = newTime.ToLongDateString();
// break;
case (int)ControlType.LabDateTimeShort:
case (int)ControlType.LabCheckDateTimeShort:
newRow[col.ColumnName] = newTime.GetDateTimeFormats('g')[0];
break;
//case "yyyyMMdd":
// newRow[col.ColumnName] = newTime.ToShortDateString().Replace("-", "");
// break;
case (int)ControlType.LabDate:
case (int)ControlType.LabCheckDateEx:
newRow[col.ColumnName] = newTime.ToShortDateString();
break;
case (int)ControlType.LabTime:
case (int)ControlType.LabCheckTime:
newRow[col.ColumnName] = newTime.ToLongTimeString();
break;
case (int)ControlType.LabShortTime:
case (int)ControlType.LabCheckShortTime:
newRow[col.ColumnName] = newTime.ToShortTimeString();
break;
case (int)ControlType.LabDateTime:
case (int)ControlType.LabCheckDateTimeEx:
newRow[col.ColumnName] = newTime;
break;
default:
newRow[col.ColumnName] = newTime;
break;
}
}
}
}
else if (decimalList.Contains(col.ColumnName))
{
GridColumn gridColumn = gridView.Columns[col.ColumnName];
string[] formatArray = gridColumn.DisplayFormat.FormatString.Split(';');
double value = 0;
Double.TryParse(row[col.ColumnName] + "", out value);
try
{
if (value == 0)
{
newRow[col.ColumnName] = "";
}
else if (value > 0)
{
newRow[col.ColumnName] = value.ToString(formatArray[0]) + "";
}
else
{
newRow[col.ColumnName] = value.ToString(formatArray[0]) + "";
}
}
catch (Exception)
{
newRow[col.ColumnName] = value;
}
}
else if (StoreValueList.Contains(col.ColumnName))
{
string fieldValue = string.Empty;
GridColumn gridColumn = gridView.Columns[col.ColumnName];
if (gridColumn.Tag is GridColumnModel)
{
GridColumnModel model = gridColumn.Tag as GridColumnModel;
if ((model.FieldType == ControlType.LabMultiSelectValue || model.FieldType == ControlType.LabMultiSelectValueNew ||
model.FieldType == ControlType.LabMultiSelectValueParam) && row[col.ColumnName].ToString().Contains(",") ||
(model.FieldType == ControlType.LabSelectReturnId && !model.IsRadio) ||
(model.FieldType == ControlType.LabSelectReturnIdNew && !model.IsRadio && model.ModuleFrameDisplayText))
{
string[] cellText = row[col.ColumnName].ToString().Split(',');
fieldValue = string.Empty;
foreach (string cellValue in cellText)
{
//fieldValue += GetValueByImportText(row, model.FieldName, cellValue, false) + ',';
fieldValue += GetValueByImportText(model, cellValue, false) + ',';
}
fieldValue = fieldValue.TrimEnd(',');
}
else
{
fieldValue = GetValueByImportText(model, row[col.ColumnName] + "" + "", false);
}
if (!string.IsNullOrWhiteSpace(fieldValue))
{
newRow[col.ColumnName] = fieldValue;
}
}
}
else
{
if (string.IsNullOrEmpty(row[col.ColumnName] + "") &&
(col.DataType == typeof(Int16) ||
col.DataType == typeof(Int32) ||
col.DataType == typeof(Int64) ||
col.DataType == typeof(Decimal) ||
col.DataType == typeof(Double)))
{
newRow[col.ColumnName] = 0;
}
else if (col.DataType == typeof(Byte[]))
{
newRow[col.ColumnName] = row[col.ColumnName] != DBNull.Value ? (Byte[])row[col.ColumnName] : null;
}
else if (col.DataType == typeof(Byte))
{
newRow[col.ColumnName] = row[col.ColumnName] != DBNull.Value ? row[col.ColumnName] : DBNull.Value;
}
else
{
newRow[col.ColumnName] = row[col.ColumnName] + "";
}
}
//处理统计
DataColumn dcIsSum = sourceTable.Columns["isSum"];
if (dcIsSum != null && !String.IsNullOrEmpty(row["isSum"] + ""))
{
int isSum = Convert.ToInt32(row["isSum"]);
int fieldType = Convert.ToInt32(row["fieldsqlTag"]);
string dataFormat = row["DataFormat"] + "";
GridColumn gridColumn = this.gridView1.Columns[col.ColumnName];
// 格式化数字
if (fieldType == ControlType.LabTextInt || fieldType == ControlType.LabCalcText)
{
gridColumn.DisplayFormat.FormatType = FormatType.Numeric;
gridColumn.DisplayFormat.FormatString = dataFormat;
}
if (isSum == 1)
{
this.gridView1.OptionsView.ShowFooter = true;
if ((row["calcExpr"] + "").IndexOf("/{") == -1)
{
gridColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), "{0:" + dataFormat + "}") });
if (SystemInfo.Instance.GroupSpecialMode)
{
this.gridView1.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), gridColumn, "{0:" + dataFormat + "}"));
this.gridView1.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
this.gridView1.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Sum, row["fieldname"].ToString(), null, "{0:" + dataFormat + "}") });
}
}
else
{
gridColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), "{0:" + dataFormat + "}") });
if (SystemInfo.Instance.GroupSpecialMode)
{
this.gridView1.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), gridColumn, "{0:" + dataFormat + "}"));
this.gridView1.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
this.gridView1.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Custom, row["fieldname"].ToString(), null, "{0:" + dataFormat + "}") });
}
}
}
}
}
}
dtTable.Rows.Add(newRow);
}
if (gridView.Columns.Count > 0)
{
GridColumn firstColumn = this.gridView1.Columns[0];
if (firstColumn != null)
{
this.gridView1.OptionsView.ShowFooter = true;
string firstFieldName = firstColumn.FieldName.ToString();
_exportCustomSummaryValues[firstFieldName] = string.Format("合计: {0}行", dtTable.Rows.Count);
firstColumn.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Custom, firstFieldName, "{0}") });
if (SystemInfo.Instance.GroupSpecialMode)
{
//this.gridView1.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, firstColumn.FieldName.ToString(), firstColumn, "合计: {0:#,###}行"));
this.gridView1.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
this.gridView1.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, firstColumn.FieldName.ToString(), null, "合计: {0:#,###}行") });
}
//底部汇总是否导出
if (SystemInfo.Instance.ExportSummary)
{
gridView.UpdateTotalSummary();
for (int i = 1; i < this.gridView1.Columns.Count; i++)
{
string columnName = this.gridView1.Columns[i].FieldName;
GridSummaryItem gsi = gridView.Columns[columnName].SummaryItem;
if (gsi.SummaryType != DevExpress.Data.SummaryItemType.None) //gsi.SummaryValue!=null&& !string.IsNullOrEmpty(gsi.SummaryValue.ToString())
{
if (gsi.SummaryType == DevExpress.Data.SummaryItemType.Custom)
{
_exportCustomSummaryValues[columnName] = GetExportSummaryValue(gridView.Columns[columnName], gsi);
}
string originalFormat = gsi.DisplayFormat;
// 匹配 {0:#.##}、{0:0.##} 等格式 避免出现没有小数但是还有小数点的情况,如 0.
try
{
var match = System.Text.RegularExpressions.Regex.Match(originalFormat, @"\{0:(.*?)\}");
if (match.Success)
{
string innerFormat = match.Groups[1].Value;
if (innerFormat.Contains(".") && innerFormat.Split(';').Length == 1)
{
// 生成条件格式:正数;负数;零(整数无小数点)
string newInnerFormat = $"{innerFormat};{innerFormat};{innerFormat.Split('.')[0]}";
originalFormat = originalFormat.Replace(innerFormat, newInnerFormat);
}
}
}
catch (Exception ex)
{
originalFormat = gsi.DisplayFormat;
}
this.gridView1.Columns[i].Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(gsi.SummaryType, this.gridView1.Columns[i].FieldName.ToString(), originalFormat) });
if (SystemInfo.Instance.GroupSpecialMode)
{
this.gridView1.GroupSummary.Add(new DevExpress.XtraGrid.GridGroupSummaryItem(gsi.SummaryType, this.gridView1.Columns[i].FieldName.ToString(), this.gridView1.Columns[i], originalFormat));
this.gridView1.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
}
else
{
this.gridView1.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(gsi.SummaryType, this.gridView1.Columns[i].FieldName.ToString(), null, gsi.DisplayFormat) });
}
}
}
}
}
}
this.gridControl1.DataSource = dtTable;
//重新设置分组信息
if (grouping.Count > 0)
{
for (int i = 0; i < grouping.Count; i++)
{
string ColumnName = grouping[i].FieldName;
GridColumn gridViewNewCol = gridView1.Columns.ColumnByFieldName(ColumnName);
if (gridViewNewCol != null) gridViewNewCol.GroupIndex = grouping[i].GroupIndex;
}
}
return this.gridControl1;
}
else
{
return control;
}
}
public CompositeLink ReplaceBitLink(params IPrintable[] panels)
{
PrintingSystem ps = new PrintingSystem();
CompositeLink link = new CompositeLink(ps);
ps.Links.Add(link);
foreach (IPrintable panel in panels)
{
link.Links.Add(CreatePrintableLink(panel));
}
link.Landscape = true;//横向
return link;
}
///
/// 创建打印Componet
///
///
///
PrintableComponentLink CreatePrintableLink(IPrintable printable)
{
ChartControl chart = printable as ChartControl;
if (chart != null)
chart.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Stretch;
PrintableComponentLink printableLink = new PrintableComponentLink() { Component = printable };
return printableLink;
}
///
/// 说明:行渲染
/// 创建人:龚宇超
/// 创建日期:2019-06-14
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0
///
/// The sender.
/// The instance containing the event data.
public void OnGridViewRowCellStyle(object sender, RowCellStyleEventArgs e)
{
if (!e.Column.OptionsColumn.AllowEdit)
{
Color color1 = ColorTranslator.FromHtml("#d0d0d0");
e.Appearance.BackColor = color1;
}
}
///
/// DataSet转换成Excel文档流
///
///
///
public MemoryStream RenderToExcel(DataSet ds)
{
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();
for (int i = 0; i < ds.Tables.Count; i++)
{
DataTable table = ds.Tables[i];
ISheet sheet = workbook.CreateSheet(table.TableName);
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
// handling value.
int rowIndex = 1;
foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
AutoSizeColumns(sheet);
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}
return ms;
}
///
/// 自动设置Excel列宽
///
/// Excel表
private void AutoSizeColumns(ISheet sheet)
{
if (sheet.PhysicalNumberOfRows > 0)
{
IRow headerRow = sheet.GetRow(0);
for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
{
sheet.AutoSizeColumn(i);
}
}
}
///
/// 保存Excel文档流到文件
///
/// Excel文档流
/// 文件名
public void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
data = null;
}
}
public Dictionary> ValueGridColumnTable;
///
/// 说明:导入表的时候将下拉框的值存储
/// 创建人:王一帆
/// 创建日期:2020-04-21
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0.0.3
///
/// The col fields.
public void InitializeValueGrid(GridView gridView)
{
try
{
ValueGridColumnTable = new Dictionary>();
//_checkColumns = new List();
//LookupParentKey = new Dictionary();
foreach (GridColumn col in gridView.Columns)
{
if (col.Tag is GridColumnModel)
{
GridColumnModel model = col.Tag as GridColumnModel;
if (model != null && !ValueGridColumnTable.ContainsKey(model))
{
if (model.FieldType == ControlType.LabMultiSelectValue
|| model.FieldType == ControlType.LabMultiSelectValueNew
|| model.FieldType == ControlType.LabTreeLookValue
|| model.FieldType == ControlType.LabMultiSelectValueParam)
{
string sqlValue = model.SqlSource;
if (!string.IsNullOrWhiteSpace(sqlValue))
{
DataTable dataTable = Business.Impl.BaseImpl.GetDataTableResult(sqlValue);
// 创建字典来存储翻译结果
//Dictionary translationDict = dataTable.AsEnumerable()
// .ToDictionary(row => row[model.ValueMember].ToString(), row => row[model.TextMember].ToString());
Dictionary translationDict = new Dictionary();
foreach (DataRow item in dataTable.Rows)
{
string key = item[model.ValueMember].ToString();
string value = item[model.TextMember].ToString();
if (!translationDict.ContainsKey(key))
{
translationDict.Add(key, value);
}
}
ValueGridColumnTable.Add(model, translationDict);
}
}
else if (model.FieldType == ControlType.LabSelectReturnId || (model.FieldType == ControlType.LabSelectReturnIdNew && model.ModuleFrameDisplayText) || model.FieldType == ControlType.LabModuleAddRowsID)
{
string sqlValue = model.SqlSource;
if ((model.IsRadio && !string.IsNullOrWhiteSpace(model.addModuleld)) || model.FieldType == ControlType.LabSelectReturnIdNew || model.FieldType == ControlType.LabModuleAddRowsID)
{
//单选模式数据源为模块sql 新版模块选中返回id固定位模块sql
DataRow modelRow = Business.Impl.MainImpl.GetSystemdllTab(model.addModuleld);
sqlValue = modelRow["SQL"] + "";
}
DataTable dataTable = Business.Impl.BaseImpl.GetDataTableResult(sqlValue);
Dictionary translationDict = new Dictionary();
foreach (DataRow item in dataTable.Rows)
{
string key = item[model.ValueMember].ToString();
string value = item[model.TextMember].ToString();
if (!translationDict.ContainsKey(key))
{
translationDict.Add(key, value);
}
}
ValueGridColumnTable.Add(model, translationDict);
}
}
}
}
}
catch (Exception ex)
{
MessageUtil.Show(ex.Message);
}
}
///
/// 说明:获取导入到下拉框里的显示值
/// 创建人:王一帆
/// 创建日期:2020-04-22
/// 修改人:
/// 修改日期:
/// 修改备注:
/// 版本:1.0.0.3
///
/// The control.
/// DataTable.
public string GetValueByImportText(GridColumnModel model, string text, bool isBillImport = false)
{
string value = text;
Dictionary translationDict = null;
if (ValueGridColumnTable.TryGetValue(model, out translationDict))
{
if (translationDict != null && translationDict.Count > 0)
{
if (translationDict.TryGetValue(text, out string translatedValue))
{
value = translatedValue;
}
else
{
value = text;
}
}
else
{
value = "";
}
}
return value;
}
}
}