/****************************** * 说明:导出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 DevExpress.XtraTreeList; using DevExpress.XtraTreeList.Columns; 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.IO; using System.Linq; using System.Windows.Forms; namespace Lskj.Control { /// /// 导出Excel窗口,用于重置数据 /// public partial class FrmTreeExport : Form { public FrmTreeExport() { InitializeComponent(); gcMain.Appearance.HeaderPanel.Font = new Font("宋体", 9); gcMain.Appearance.HeaderPanel.TextOptions.HAlignment = HorzAlignment.Center; gcMain.Appearance.Preview.Font = new Font("宋体", 9); gcMain.Appearance.Row.Font = new Font("宋体", 9); //gcMain.OptionsView.RowAutoHeight = true; //gcMain.RowCellStyle += new RowCellStyleEventHandler(OnGridViewRowCellStyle); Lskj.Control.Model.AutoSizeChange.ControllInitializeSize(this); } /// /// 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; } /// /// 说明:复制为新表格(树表格) /// 创建人:曹屹峰 /// 创建日期:2024-07-26 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The control. /// GridControl. public TreeList ReplaceBitColumn(TreeList control, bool IsCustomColumn = false) { //GridView gridView = new GridView(); this.gcMain.ParentFieldName = control.ParentFieldName; this.gcMain.KeyFieldName = control.KeyFieldName; bool hasBoolean = false; List boolList = new List(); List datetimeList = new List(); List decimalList = new List(); List visibleList = new List(); Dictionary dictionary = new Dictionary(); List StoreValueList = new List(); InitializeValueGrid(control); foreach (TreeListColumn col in control.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.Format.FormatString.Contains(';') && col.Format.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)) { StoreValueList.Add(col.FieldName); } } if (hasBoolean || IsCustomColumn) { // 复制列 foreach (TreeListColumn col in control.Columns) { GridColumnModel gridModel = col.Tag as GridColumnModel; if (col.Visible && !col.FieldName.Equals("RightMenuBtnEdit")) { TreeListColumn newCol = new TreeListColumn(); newCol.Tag = col.Tag; newCol.Caption = col.Caption; 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; //this.gcMain.Columns.Add(newCol); this.gcMain.Columns.AddRange(new TreeListColumn[] { newCol }); visibleList.Add(col.FieldName); if (gridModel != null && !dictionary.ContainsKey(col.FieldName)) { dictionary.Add(col.FieldName, gridModel.FieldType); } } } DataTable sourceTable = control.DataSource as DataTable; //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; TreeListColumn gridColumn = this.gcMain.Columns[col.ColumnName]; if (decimalList.Contains(col.ColumnName)) { newCol.DataType = typeof(String); } if (datetimeList.Contains(col.ColumnName)) { newCol.DataType = typeof(DateTime); } 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)) { TreeListColumn gridColumn = control.Columns[col.ColumnName]; string[] formatArray = gridColumn.Format.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; TreeListColumn gridColumn = control.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(','); 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"] + ""; // TreeListColumn gridColumn = this.gcMain.Columns[col.ColumnName]; // // 格式化数字 // if (fieldType == ControlType.LabTextInt || fieldType == ControlType.LabCalcText) // { // gridColumn.Format.FormatType = FormatType.Numeric; // gridColumn.Format.FormatString = dataFormat; // } // if (isSum == 1) // { // gcMain.OptionsView.ShowSummaryFooter = true; // gridColumn.AllNodesSummary = true; // gridColumn.SummaryFooter = DevExpress.XtraTreeList.SummaryItemType.Sum; // gridColumn.SummaryFooterStrFormat = "{0:" + dataFormat + "}"; // } //} } } dtTable.Rows.Add(newRow); } //if (gridView.Columns.Count > 0) //{ // TreeListColumn firstColumn = this.gcMain.Columns[0]; // if (firstColumn != null) // { // gcMain.OptionsView.ShowSummaryFooter = true; // firstColumn.AllNodesSummary = true; // firstColumn.SummaryFooter = SummaryItemType.Count; // firstColumn.SummaryFooterStrFormat = "合计:{0:#,###}行"; // //底部汇总是否导出 // if (SystemInfo.Instance.ExportSummary) // { // for (int i = 1; i < this.gcMain.Columns.Count; i++) // { // string columnName = this.gcMain.Columns[i].FieldName; // GridSummaryItem gsi = gridView.Columns[columnName].SummaryItem; // if (gsi.SummaryType != DevExpress.Data.SummaryItemType.None) //gsi.SummaryValue!=null&& !string.IsNullOrEmpty(gsi.SummaryValue.ToString()) // { // this.gcMain.Columns[i].Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridColumnSummaryItem(gsi.SummaryType, this.gridView1.Columns[i].FieldName.ToString(), gsi.DisplayFormat) }); // this.gcMain.GroupSummary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] { new DevExpress.XtraGrid.GridGroupSummaryItem(gsi.SummaryType, this.gridView1.Columns[i].FieldName.ToString(), null, gsi.DisplayFormat) }); // } // } // } // } //} this.gcMain.DataSource = dtTable; return this.gcMain; } 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(TreeList treeList) { try { ValueGridColumnTable = new Dictionary>(); foreach (TreeListColumn col in treeList.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) { 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); } } } } } } 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; } } }