public SpreadsheetGear.IWorkbook generarReporte(string nombreHoja, List <string> titulos, List <List <string> > contenido) { // Create a new workbook. SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(); SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"]; SpreadsheetGear.IRange cells = worksheet.Cells; // Set the worksheet name. if (nombreHoja.Length > 31) { worksheet.Name = nombreHoja.Replace('/', '-').Substring(0, 31); } else { worksheet.Name = nombreHoja.Replace('/', '-'); } string ultimaColumna = ""; int tituloIndex = 1; // Load column titles. for (char c = 'A'; tituloIndex <= titulos.Count(); c++) { cells[c.ToString() + "1"].Formula = titulos[tituloIndex - 1]; if (tituloIndex == titulos.Count()) { ultimaColumna = c.ToString(); } tituloIndex++; } //centra los titulos del reporte cells["A1:" + ultimaColumna + "1"].HorizontalAlignment = SpreadsheetGear.HAlign.Center; //carga el contenido del reporte for (int i = 0; i < contenido.Count; i++) { for (int j = 0; j < contenido[i].Count; j++) { // 65 = 'A', 66 = 'B', etc. Empieza en la A2, B2, C2 ... y luego cambia de fila string celda = (char)(j + 65) + (i + 2).ToString(); cells[celda].Formula = contenido[i][j]; } } cells["A1:" + ultimaColumna + "100"].Columns.AutoFit(); // Stream the Excel spreadsheet to the client in a format // compatible with Excel 97/2000/XP/2003/2007/2010. return(workbook); }
public IActionResult DownloadReport() { // Create a new workbook. SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(); SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"]; SpreadsheetGear.IRange cells = worksheet.Cells; // Set the worksheet name. worksheet.Name = "2005 Sales"; // Load column titles and center. cells["B1"].Formula = "North"; cells["C1"].Formula = "South"; cells["D1"].Formula = "East"; cells["E1"].Formula = "West"; cells["B1:E1"].HorizontalAlignment = SpreadsheetGear.HAlign.Center; // Load row titles using multiple cell text reference and iteration. int quarter = 1; foreach (SpreadsheetGear.IRange cell in cells["A2:A5"]) { cell.Formula = "Q" + quarter++; } // Load random data and format as $ using a multiple cell range. SpreadsheetGear.IRange body = cells[1, 1, 4, 4]; body.Formula = "=RAND() * 10000"; body.NumberFormat = "$#,##0_);($#,##0)"; // Save workbook to an Open XML (XLSX) workbook stream. System.IO.Stream stream = workbook.SaveToStream( SpreadsheetGear.FileFormat.OpenXMLWorkbook); // Reset stream's current position back to the beginning. stream.Seek(0, System.IO.SeekOrigin.Begin); // Stream the Excel spreadsheet to the client in a format // compatible with Excel 97/2000/XP/2003/2007/2010/2013/2016. return(new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")); }
private void SetParameters() { string xlsPath; SpreadsheetGear.IWorkbook workbook = null; SpreadsheetGear.IWorksheet sheet = null; SpreadsheetGear.IRange range = null; SetStatus("Setting Parameter Data"); try { xlsPath = EnsureXLSFile(); workbook = SpreadsheetGear.Factory.GetWorkbook(xlsPath); sheet = workbook.Worksheets["Data"]; foreach (string key in m_Inputs.Parameters.Keys) { range = null; try { range = sheet.Cells[key]; } catch (Exception) { } if (range != null) { range.Value = m_Inputs.Parameters[key]; } } workbook.WorkbookSet.CalculateFull(); workbook.Save(); } finally { workbook?.Close(); } }
/// <summary> /// Export metadata to excel file /// </summary> /// <param name="ExcelFilePath">Excel File Path to be written as export data</param> public void ExportMetaDataToExcel(string ExcelFilePath, MetadataElementType elementType, string elementName, string elementGId, int targetElementNID) { try { // --Open excel and get first worksheet this.DiExcel = new DIExcel(ExcelFilePath); MetadataSheet = DiExcel.GetWorksheet(0); // --Set Matadata Type in Cell 0,0 switch (elementType) { case MetadataElementType.Indicator: SetMetadataCommonCellValues(DILanguage.GetLanguageString("INDICATOR") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; case MetadataElementType.Area: SetMetadataCommonCellValues(DILanguage.GetLanguageString("AREA") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; case MetadataElementType.Source: SetMetadataCommonCellValues(DILanguage.GetLanguageString("SOURCE") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; default: break; } // --Load data from xml to excel file this.LoadData(elementType, targetElementNID); //-- Save excel this.DiExcel.Save(); } catch (Exception ex) { } }
public static void Main(string[] Pages) { XmlReader reader = XmlReader.Create(Pages[0]); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, string>)); Dictionary <string, string> list = (Dictionary <string, string>)serializer.ReadObject(reader); reader.Close(); SpreadsheetGear.Windows.Forms.WorkbookView WV = new SpreadsheetGear.Windows.Forms.WorkbookView(); FeuerwehrCloud.Helper.Logger.WriteLine("| > [ExcelPrinter] *** Opening " + Pages[1]); WV.ActiveWorkbook = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.Open(Pages[1]); WV.GetLock(); SpreadsheetGear.IWorksheet WB = WV.ActiveWorkbook.Worksheets [0]; for (int x = 0; x < 25; x++) { for (int y = 0; y < 25; y++) { SpreadsheetGear.IRange IR = WB.Cells [x, y]; string CValue = IR.Text; try { if (CValue == "#EINSATZORT#") { IR.Value = list["EinsatzOrt"]; } } catch (Exception e1) { } try { if (CValue == "#EINSATZNR#") { IR.Value = list["EinsatzNr"]; } } catch (Exception e1) { } try { if (CValue == "#EINSATZSTRASSE#") { IR.Value = list["EinsatzStrasse"]; } } catch (Exception e1) { } try { if (CValue == "#EINSATZABSCHNITT#") { IR.Value = list["EinsatzAbschnitt"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZKREUZUNG#") { IR.Value = list["EinsatzKreuzung"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZOBJEKT#") { IR.Value = list["EinsatzObjekt"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZBMERKUNG#") { IR.Value = list["EinsatzBemerkung"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZPRIORITAET#") { IR.Value = list["EinsatzPrioritaet"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZSTICHWORT#") { IR.Value = list["EinsatzStichwort"]; } } catch (Exception e1) { } try { if (IR.Value == "#EINSATZSCHLAGWORT#") { IR.Value = list["EinsatzSchlagwort"]; } } catch (Exception e1) { } try { if (IR.Value == "#DATUM#") { IR.Value = System.DateTime.Now.ToString("d"); } } catch (Exception e1) { } } } WB.PageSetup.LeftMargin = 0; WB.PageSetup.RightMargin = 0; WB.PageSetup.TopMargin = 0; WB.PageSetup.BottomMargin = 0; WB.PageSetup.PaperSize = SpreadsheetGear.PaperSize.A4; WB.PageSetup.FitToPagesWide = 1; WV.ReleaseLock(); WV.Print(false); WV.GetLock(); WV.ActiveWorkbook.Close(); }
static void Main(string[] args) { SpreadsheetGear.IWorkbook gear = SpreadsheetGear.Factory.GetWorkbook(); SpreadsheetGear.IWorksheet worksheet = gear.Worksheets.Add(); SpreadsheetGear.IWorksheetWindowInfo windowInfo = worksheet.WindowInfo; // Load some sample data. SpreadsheetGear.IRange dataRange = worksheet.Cells["A1:B6"]; dataRange.Value = new string[, ] { { "A", "$7,923" }, { "B", "$5,954" }, { "C", "$5,522" }, { "D", "$3,701" }, { "E", "$5,522" }, { "F", "$3,701" } }; SpreadsheetGear.Shapes.IShape shape = worksheet.Shapes.AddChart(0, 0, 100, 100); SpreadsheetGear.Charts.IChart chart = shape.Chart; chart.SetSourceData(dataRange, SpreadsheetGear.Charts.RowCol.Columns); chart.ChartType = SpreadsheetGear.Charts.ChartType.ColumnStacked; chart.ChartGroups[0].GapWidth = 50; chart.HasTitle = false; chart.HasLegend = false; chart.PlotVisibleOnly = true; chart.ChartArea.Font.Color = SpreadsheetGear.Color.FromArgb(178, 178, 178); chart.SeriesCollection[0].HasDataLabels = false; chart.SeriesCollection[0].HasLeaderLines = false; chart.SeriesCollection[0].MarkerStyle = SpreadsheetGear.Charts.MarkerStyle.Automatic; shape = worksheet.Shapes.AddChart(500, 500, 600, 600); chart = shape.Chart; chart.SetSourceData(dataRange, SpreadsheetGear.Charts.RowCol.Columns); chart.ChartType = SpreadsheetGear.Charts.ChartType.Pie; SpreadsheetGear.Charts.ISeries series = chart.SeriesCollection[0]; series.XValues = dataRange; // Add series data labels and change to show percentage only. series.HasDataLabels = true; series.DataLabels.ShowPercentage = true; series.DataLabels.ShowValue = false; series.DataLabels.ShowCategoryName = false; worksheet.Cells["F3"].NumberFormat = @"_-* #,##0.00_-;-* #,##0.00_-;_-@_-"; worksheet.Cells["F3"].Value = 3553654566.641; worksheet.Cells["F6"].Font.Color = SpreadsheetGear.Color.FromArgb(178, 178, 178); worksheet.Cells["F6"].Font.Name = "Webdings"; worksheet.Cells["F6"].Value = "a"; worksheet.Cells["F9"].Font.Color = SpreadsheetGear.Color.FromArgb(178, 178, 178); worksheet.Cells["F9"].Font.Name = "Webdings"; worksheet.Cells["F9"].Value = "r"; gear.SaveAs(@"D:\Excels.xls", SpreadsheetGear.FileFormat.OpenXMLWorkbook); }
/// <summary> /// Get Metadata from Excel File /// </summary> /// <remarks> /// This method will Extract Metadata from excel file and make a string Containing Matadata in Xml Format . /// So this can be stored in database /// </remarks> public String GetMetadataFromExcelFile(string excelFilePath, MetaDataType elementType, string fldrMetadataTemplatePath) { // Step 1 : Open Excel File for reading // Step2 : Get Mask and blank Metadata xml file from metadata template Folder // Step3 : Update Blank Metadata file from metadata found in excel file. Metadata will be inserted in xml using // Position and path definded in Mask file. string RetVal = String.Empty; //Step1. Open excel File // Open excel and get first worksheet this.DiExcel = new DIExcel(excelFilePath); MetadataSheet = DiExcel.GetWorksheet(0); // Matadata starts from 5th Row //this._MetadataStartRowIndexInExl = 4; // step2: Get Mask and blank xml file from Metadata Template Folder /////GetMetadataTemplateFilesForImport(elementType, fldrMetadataTemplatePath); // Step3: Update metadata blank document using metadata found in metadata excel. // Import will be done using Mask File. So check for Mask file //if (this._MetadataMaskFilePath.Length > 0 && File.Exists(this._MetadataMaskFilePath)) //{ // if (this._MetadataFilePath.Length > 0 && File.Exists(this._MetadataFilePath)) // { // int i = 0; // XmlNode xn = null; // XmlNodeList xnList = null; // try // { // int temp = 0; // // Load Blank xml Structure as Metadata file // MetadataDOM = new XmlDocument(); // MetadataDOM.Load(this._MetadataFilePath); // // Load Mask File // MetadataMaskDOM.Load(this._MetadataMaskFilePath); // // Iterate all child elements of mask file. // for (i = 0; i < MetadataMaskDOM.DocumentElement.ChildNodes.Count; i++) // { // try // { // // Get Position and path information for Metadata // string[] nodes = MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Path")[0].InnerXml.Split('/'); // string[] position = MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Position")[0].InnerXml.Split('/'); // if (position.Length < 1) // { // } // else if (position.Length == 1) // { // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // //dom.DocumentElement.InnerXml = this.rtbDataValue[temp].Text; // MetadataDOM.DocumentElement.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // //dom.DocumentElement.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = this.rtbDataValue[temp].Text; // MetadataDOM.DocumentElement.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // else if (position.Length >= 2) // { // // Get the postion of n is postion array // int npos = position.Length; // //--check which position has the n // for (int l = 1; l < position.Length; l++) // { // if (position[l] == "n") // { // npos = l; // break; // } // } // // Select Root Node Like "Indicator_Info" // // Xnlist contain list of all node under rootNode like indicator_Info // xnList = MetadataDOM.DocumentElement.SelectNodes(nodes[1]); // xnList = MetadataDOM.DocumentElement.SelectNodes(nodes[1]); // // Handling for second Postion // // If n is not at second Postion then then start from node first child under Indicator_Info(Document Element) // if (position[1] != "n") // { // xn = xnList[Convert.ToInt32(position[1]) - 1]; // } // else // { // xn = MetadataDOM.DocumentElement; // } // // Iterate inside this node. till we reach at n postion // //--get the value of xn till the nth position // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // for (int j = 2; j < npos; j++) // { // XmlNodeList xnTempList; // // Getting List of all child nodes . // // If our path nodes array contain Indicator_Info,Row1,FLD_VAL,ROWData,temp1 // //In First Iteration we selcted all Fld_Val node under Row1 // // In SEcond Iteration we select AllRowDAta node under FLD_Val // // Continue until j= postion of n .So we have all nodes inside nodelist for which n is applied // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // // Insert metadata value // if (npos == position.Length) // { // //xn.InnerXml = this.rtbDataValue[temp].Text; // xn.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // for (int j = 2; j < npos - 1; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // if (npos == position.Length) // { // xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // //--get the value of the nodes from the nth position // if (npos < position.Length) // { // // Get all row data for which we have n in position // xnList = xn.SelectNodes(nodes[npos]); // //xnlist is value for total no of metadata paragraph required // for (int o = 0; o < xnList.Count; o++) // { // try // { // xn = xnList[o]; // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // // Handling for after n node // for (int j = npos + 1; j < nodes.Length; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // // Get Value of each metadata // // xn.InnerXml = SetCharacterEntities(this.rtbDataValue[temp].Text); // xn.InnerXml = SetCharacterEntities(this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1).ToString()); // temp++; // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // for (int j = npos + 1; j < nodes.Length - 1; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // //xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = SetCharacterEntities(this.rtbDataValue[temp].Text); // xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = SetCharacterEntities(this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1).ToString()); // temp++; // } // } // catch (Exception ex) // { // } // } // } // } // } // catch (Exception ex) // { // } // } // // Get Metadata Text in RetVal // RetVal = MetadataDOM.InnerXml; //MetadataDOM.Save(xmlFile); // DiExcel.Close(); // } // catch (Exception ex) // { // RetVal = String.Empty; // DiExcel.Close(); // } // } //} return RetVal; }
/// <summary> /// Export metadata to excel file /// </summary> /// <param name="ExcelFilePath">Excel File Path to be written as export data</param> public void ExportMetaDataToExcel(string ExcelFilePath, MetadataElementType elementType, string elementName, string elementGId,int targetElementNID) { try { // --Open excel and get first worksheet this.DiExcel = new DIExcel(ExcelFilePath); MetadataSheet = DiExcel.GetWorksheet(0); // --Set Matadata Type in Cell 0,0 switch (elementType) { case MetadataElementType.Indicator: SetMetadataCommonCellValues(DILanguage.GetLanguageString("INDICATOR") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; case MetadataElementType.Area: SetMetadataCommonCellValues(DILanguage.GetLanguageString("AREA") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; case MetadataElementType.Source: SetMetadataCommonCellValues(DILanguage.GetLanguageString("SOURCE") + "-" + DILanguage.GetLanguageString("METADATA"), elementName, elementGId); break; default: break; } // --Load data from xml to excel file this.LoadData(elementType,targetElementNID); //-- Save excel this.DiExcel.Save(); } catch (Exception ex) { } }
// 导出excel模板 private void efBtn_export_model_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 2; saveFileDialog.RestoreDirectory = true; saveFileDialog.FileName = "Template"; try { if (saveFileDialog.ShowDialog(this) == DialogResult.OK) { #if (Devxpress) if (m_ctrlGrid is GridControl) { GridControl currentGridControl = m_ctrlGrid as GridControl; GridView currentGridView = currentGridControl.FocusedView as GridView; DataSet dsSource = currentGridControl.DataSource as DataSet; if (dsSource == null) { return; } DataTable dtExport = dsSource.Tables[currentGridControl.DataMember].Clone(); int index = 0; for (index = 1; index < currentGridView.VisibleColumns.Count; ++index) { string strColEname = currentGridView.VisibleColumns[index].FieldName; if (!dtExport.Columns.Contains(strColEname)) { dtExport.Columns.Add(strColEname); //dtExport.Columns[strColEname].SetOrdinal(index - 1); } else if (string.IsNullOrEmpty(strColEname.Trim())) { dtExport.Columns.Add(currentGridView.VisibleColumns[index].Name); } } index--; //while (index < dtExport.Columns.Count) //{ // dtExport.Columns.RemoveAt(index); //} SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(); SpreadsheetGear.IWorksheet workSheet = workbook.Worksheets[0]; workSheet.Name = string.IsNullOrEmpty(dtExport.TableName) ? "tmp" : dtExport.TableName; for (index = 0; index < dtExport.Columns.Count; ++index) { if (efRB_col_cname.Checked || efRB_col_seq.Checked) { string strCaption = ""; if (null != currentGridView.Columns.ColumnByFieldName(dtExport.Columns[index].ColumnName)) { strCaption = currentGridView.Columns.ColumnByFieldName(dtExport.Columns[index].ColumnName).Caption; } else { continue; } strCaption = strCaption.Replace("<br>", ""); workSheet.Cells[0, index].Formula = strCaption.Replace(" ", ""); } else { workSheet.Cells[0, index].Formula = dtExport.Columns[index].ColumnName; } workSheet.Cells[0, index].Columns.AutoFit(); workSheet.Cells[0, index].Interior.Color = Color.Gray; workSheet.Cells[0, index].Borders.LineStyle = SpreadsheetGear.LineStyle.Continuous; SpreadsheetGear.IRange iColumnRange = workSheet.Cells[0, index].EntireColumn; if (dtExport.Columns[index].DataType == typeof(DateTime)) { GridColumn gridColumn = currentGridView.Columns.ColumnByFieldName(dtExport.Columns[index].ColumnName); iColumnRange.NumberFormat = gridColumn.DisplayFormat.FormatString; } else if (dtExport.Columns[index].DataType == typeof(string)) { iColumnRange.NumberFormat = "@"; } } dtExport.Merge(dsSource.Tables[currentGridControl.DataMember], true, MissingSchemaAction.Ignore); dtExport.AcceptChanges(); if (dtExport.Rows.Count > 0) { SpreadsheetGear.IRange range = workSheet.Cells["A2"]; range.CopyFromDataTable(dtExport, SpreadsheetGear.Data.SetDataFlags.NoColumnHeaders); } workbook.SaveAs(saveFileDialog.FileName, SpreadsheetGear.FileFormat.XLS97); return; } #endif if (m_ctrlGrid is DataGridView) { DataGridView currentGridControl = m_ctrlGrid as DataGridView; DataTable dsSource = currentGridControl.DataSource as DataTable; if (dsSource == null) { return; } DataTable dtExport = dsSource.Clone(); int index = 0; for (index = 1; index < currentGridControl.Columns.Count; ++index) { string strColEname = currentGridControl.Columns[index].Name; if (!dtExport.Columns.Contains(strColEname)) { dtExport.Columns.Add(strColEname); //dtExport.Columns[strColEname].SetOrdinal(index - 1); } } //index--; //while (index < dtExport.Columns.Count) //{ // dtExport.Columns.RemoveAt(index); //} SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(); SpreadsheetGear.IWorksheet workSheet = workbook.Worksheets[0]; workSheet.Name = string.IsNullOrEmpty(dtExport.TableName) ? "tmp" : dtExport.TableName; for (index = 0; index < dtExport.Columns.Count; ++index) { if (efRB_col_cname.Checked || efRB_col_seq.Checked) { string strCaption = currentGridControl.Columns[dtExport.Columns[index].ColumnName].HeaderText; strCaption = strCaption.Replace("<br>", ""); workSheet.Cells[0, index].Formula = strCaption.Replace(" ", ""); } else { workSheet.Cells[0, index].Formula = dtExport.Columns[index].ColumnName; } workSheet.Cells[0, index].Columns.AutoFit(); workSheet.Cells[0, index].Interior.Color = Color.Gray; workSheet.Cells[0, index].Borders.LineStyle = SpreadsheetGear.LineStyle.Continuous; SpreadsheetGear.IRange iColumnRange = workSheet.Cells[0, index].EntireColumn; if (dtExport.Columns[index].DataType == typeof(DateTime)) { //GridColumn gridColumn = currentGridControl.Columns[dtExport.Columns[index].ColumnName].di //iColumnRange.NumberFormat = gridColumn.DisplayFormat.FormatString; } else if (dtExport.Columns[index].DataType == typeof(string)) { iColumnRange.NumberFormat = "@"; } } dtExport.Merge(dsSource, true, MissingSchemaAction.Ignore); dtExport.AcceptChanges(); if (dtExport.Rows.Count > 0) { SpreadsheetGear.IRange range = workSheet.Cells["A2"]; range.CopyFromDataTable(dtExport, SpreadsheetGear.Data.SetDataFlags.NoColumnHeaders); } workbook.SaveAs(saveFileDialog.FileName, SpreadsheetGear.FileFormat.XLS97); return; } } } catch (Exception ex) { MessageBox.Show(ex.StackTrace); } }
/// <summary> /// Get Metadata from Excel File /// </summary> /// <remarks> /// This method will Extract Metadata from excel file and make a string Containing Matadata in Xml Format . /// So this can be stored in database /// </remarks> public String GetMetadataFromExcelFile(string excelFilePath, MetaDataType elementType, string fldrMetadataTemplatePath) { // Step 1 : Open Excel File for reading // Step2 : Get Mask and blank Metadata xml file from metadata template Folder // Step3 : Update Blank Metadata file from metadata found in excel file. Metadata will be inserted in xml using // Position and path definded in Mask file. string RetVal = String.Empty; //Step1. Open excel File // Open excel and get first worksheet this.DiExcel = new DIExcel(excelFilePath); MetadataSheet = DiExcel.GetWorksheet(0); // Matadata starts from 5th Row //this._MetadataStartRowIndexInExl = 4; // step2: Get Mask and blank xml file from Metadata Template Folder /////GetMetadataTemplateFilesForImport(elementType, fldrMetadataTemplatePath); // Step3: Update metadata blank document using metadata found in metadata excel. // Import will be done using Mask File. So check for Mask file //if (this._MetadataMaskFilePath.Length > 0 && File.Exists(this._MetadataMaskFilePath)) //{ // if (this._MetadataFilePath.Length > 0 && File.Exists(this._MetadataFilePath)) // { // int i = 0; // XmlNode xn = null; // XmlNodeList xnList = null; // try // { // int temp = 0; // // Load Blank xml Structure as Metadata file // MetadataDOM = new XmlDocument(); // MetadataDOM.Load(this._MetadataFilePath); // // Load Mask File // MetadataMaskDOM.Load(this._MetadataMaskFilePath); // // Iterate all child elements of mask file. // for (i = 0; i < MetadataMaskDOM.DocumentElement.ChildNodes.Count; i++) // { // try // { // // Get Position and path information for Metadata // string[] nodes = MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Path")[0].InnerXml.Split('/'); // string[] position = MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Position")[0].InnerXml.Split('/'); // if (position.Length < 1) // { // } // else if (position.Length == 1) // { // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // //dom.DocumentElement.InnerXml = this.rtbDataValue[temp].Text; // MetadataDOM.DocumentElement.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // //dom.DocumentElement.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = this.rtbDataValue[temp].Text; // MetadataDOM.DocumentElement.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // else if (position.Length >= 2) // { // // Get the postion of n is postion array // int npos = position.Length; // //--check which position has the n // for (int l = 1; l < position.Length; l++) // { // if (position[l] == "n") // { // npos = l; // break; // } // } // // Select Root Node Like "Indicator_Info" // // Xnlist contain list of all node under rootNode like indicator_Info // xnList = MetadataDOM.DocumentElement.SelectNodes(nodes[1]); // xnList = MetadataDOM.DocumentElement.SelectNodes(nodes[1]); // // Handling for second Postion // // If n is not at second Postion then then start from node first child under Indicator_Info(Document Element) // if (position[1] != "n") // { // xn = xnList[Convert.ToInt32(position[1]) - 1]; // } // else // { // xn = MetadataDOM.DocumentElement; // } // // Iterate inside this node. till we reach at n postion // //--get the value of xn till the nth position // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // for (int j = 2; j < npos; j++) // { // XmlNodeList xnTempList; // // Getting List of all child nodes . // // If our path nodes array contain Indicator_Info,Row1,FLD_VAL,ROWData,temp1 // //In First Iteration we selcted all Fld_Val node under Row1 // // In SEcond Iteration we select AllRowDAta node under FLD_Val // // Continue until j= postion of n .So we have all nodes inside nodelist for which n is applied // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // // Insert metadata value // if (npos == position.Length) // { // //xn.InnerXml = this.rtbDataValue[temp].Text; // xn.InnerXml = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // for (int j = 2; j < npos - 1; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // if (npos == position.Length) // { // xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1); // temp++; // } // } // //--get the value of the nodes from the nth position // if (npos < position.Length) // { // // Get all row data for which we have n in position // xnList = xn.SelectNodes(nodes[npos]); // //xnlist is value for total no of metadata paragraph required // for (int o = 0; o < xnList.Count; o++) // { // try // { // xn = xnList[o]; // if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Element") // { // // Handling for after n node // for (int j = npos + 1; j < nodes.Length; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // // Get Value of each metadata // // xn.InnerXml = SetCharacterEntities(this.rtbDataValue[temp].Text); // xn.InnerXml = SetCharacterEntities(this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1).ToString()); // temp++; // } // else if (MetadataMaskDOM.DocumentElement.ChildNodes[i].SelectNodes("Type")[0].InnerXml == "Attribute") // { // for (int j = npos + 1; j < nodes.Length - 1; j++) // { // XmlNodeList xnTempList; // xnTempList = xn.SelectNodes(nodes[j]); // xn = xnTempList[Convert.ToInt32(position[j]) - 1]; // } // //xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = SetCharacterEntities(this.rtbDataValue[temp].Text); // xn.Attributes.GetNamedItem(nodes[nodes.Length - 1]).Value = SetCharacterEntities(this.DiExcel.GetCellValue(0, this._MetadataStartRowIndexInExl + temp, 1, this._MetadataStartRowIndexInExl + temp, 1).ToString()); // temp++; // } // } // catch (Exception ex) // { // } // } // } // } // } // catch (Exception ex) // { // } // } // // Get Metadata Text in RetVal // RetVal = MetadataDOM.InnerXml; //MetadataDOM.Save(xmlFile); // DiExcel.Close(); // } // catch (Exception ex) // { // RetVal = String.Empty; // DiExcel.Close(); // } // } //} return(RetVal); }
public void Generate() { string ruc = string.Empty; string name = string.Empty; string email = string.Empty; int beforeMonth = Month; int currentYear = Year; int valueInt = 0; decimal valueDecimal = 0; int counterWorked = 0; SpreadsheetGear.IRange range = null; SpreadsheetGear.IWorksheet wsSource = null; SpreadsheetGear.IWorksheet wsTarget = null; //Retrieving Template and Source SpreadsheetGear.IWorkbook wbSource = SpreadsheetGear.Factory.GetWorkbook($@"{FileSource}"); List <string> codesSelected = new List <string>(); wsSource = wbSource.Worksheets[1]; if (Method == MethodReport.Random) { for (int i = 1; i <= RandomNumber; i++) { codesSelected.Add(wsSource.Cells[i, 0].Value.ToString()); } //while (codesSelected.Count < RandomNumber) //{ // int randonRowIndex = new Random().Next(1, 617); // if (!codesSelected.Contains(wsSource.Cells[randonRowIndex, 0].Value.ToString())) //} } else { codesSelected.Add(CodeStore); } wsSource = wbSource.Worksheets[0]; wsSource.Cells["G3"].Formula = wsSource.Cells["D3"].Formula.Replace("4", "3"); wsSource.Cells["H3"].Formula = wsSource.Cells["D3"].Formula.Replace("4", "36"); SpreadsheetGear.Drawing.Color basicColor = SpreadsheetGear.Drawing.Color.FromArgb(89, 89, 89); SpreadsheetGear.Drawing.Color blueColor = SpreadsheetGear.Drawing.Color.FromArgb(0, 112, 192); SpreadsheetGear.Drawing.Color orangeColor = SpreadsheetGear.Drawing.Color.FromArgb(255, 153, 51); this.TotalWork = codesSelected.Count; this.ProgressFinished = counterWorked; foreach (string code in codesSelected) { SpreadsheetGear.IWorkbook wbTarget = SpreadsheetGear.Factory.GetWorkbook($@"{System.AppDomain.CurrentDomain.BaseDirectory}\Resources\{FileTemplate}"); wbSource.WorkbookSet.Calculation = SpreadsheetGear.Calculation.Manual; wsSource = wbSource.Worksheets[0]; //Update Data from Excel range = wsSource.Cells["C3"]; range.Value = code; wbSource.WorkbookSet.Calculate(); wbSource.Save(); ruc = wsSource.Cells["G3"].Value?.ToString(); name = wsSource.Cells["D3"].Value?.ToString().Replace(".", string.Empty); email = wsSource.Cells["H3"].Value?.ToString(); NameActual = name; wsTarget = wbTarget.Worksheets[0]; wsTarget.Shapes["MAIN_WARNING1"].TextFrame.Characters.Font.Color = basicColor; wsTarget.Shapes["MAIN_WARNING2"].TextFrame.Characters.Font.Color = basicColor; // C12, C13, C14 beforeMonth = Month; currentYear = Year; valueInt = 0; valueDecimal = 0; for (int i = 14; i > 1; i--, beforeMonth--) // begin at Pos 14 { if (beforeMonth == 0) { currentYear -= 1; beforeMonth = 12; } range = wsSource.Cells[11, i]; // Row 11 range.Value = $"{beforeMonth}/{currentYear}"; } #region Setting Info wsTarget.Cells["AT7"].Value = FormatMonthYear(Month, Year); wsTarget.Cells["J9"].Value = wsSource.Cells["D3"].Value.ToString(); wsTarget.Cells["J10"].Value = wsSource.Cells["E3"].Value.ToString() + ", " + wsSource.Cells["F3"].Value.ToString(); wsTarget.Cells["J11"].Value = $"Comercio: {code}"; #endregion #region MainData // Main int index = 2; valueDecimal = 0; Decimal.TryParse(wsSource.Cells[5, 3].Value.ToString(), out valueDecimal); wsTarget.Cells["P24"].Value = (valueDecimal).ToString("N0"); Decimal.TryParse(wsSource.Cells[8, 3].Value.ToString(), out valueDecimal); wsTarget.Cells["P28"].Value = (valueDecimal).ToString("N0"); valueDecimal = 0; Decimal.TryParse(wsSource.Cells[5, 4].Value.ToString(), out valueDecimal); wsTarget.Cells["Y24"].Value = (valueDecimal).ToString("N0"); Decimal.TryParse(wsSource.Cells[8, 4].Value.ToString(), out valueDecimal); wsTarget.Cells["Y28"].Value = (valueDecimal).ToString("N0"); valueDecimal = 0; Decimal.TryParse(wsSource.Cells[5, 5].Value.ToString(), out valueDecimal); wsTarget.Cells["AH24"].Value = (valueDecimal).ToString("N0"); Decimal.TryParse(wsSource.Cells[8, 5].Value.ToString(), out valueDecimal); wsTarget.Cells["AH28"].Value = (valueDecimal).ToString("N0"); valueDecimal = 0; Decimal.TryParse(wsSource.Cells[5, 6].Value.ToString(), out valueDecimal); wsTarget.Cells["AQ24"].Value = (valueDecimal).ToString("N0"); Decimal.TryParse(wsSource.Cells[8, 6].Value.ToString(), out valueDecimal); wsTarget.Cells["AQ28"].Value = (valueDecimal).ToString("N0"); wsTarget = wbTarget.Worksheets[2]; wbSource.WorkbookSet.Calculate(); wbSource.Save(); #endregion #region Graphic 2 wsTarget = wbTarget.Worksheets[0]; wsTarget = wbTarget.Worksheets[2]; decimal lastYearmonth = 0; decimal actualMonth = 0; decimal sum3PreviousMonths = 0; DateTime?dateValue = null; for (var i = 2; i < 15; i++) { dateValue = ParseDateXlsToDateTime(int.Parse(wsSource.Cells[11, i].Value.ToString())); wsTarget.Cells[4, i].Value = FormatMonthYear(dateValue.Value.Month, dateValue.Value.Year, true); // headerDates valueDecimal = 0; range = wsSource.Cells[12, i]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells[5, i].Value = valueDecimal; if (i == 2) { lastYearmonth = valueDecimal; } else if (i == 14) { actualMonth = valueDecimal; } else if (i >= 11 && i < 14) { sum3PreviousMonths += valueDecimal; // sum of 3 previous months } valueDecimal = 0; range = wsSource.Cells[13, i]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells[6, i].Value = valueDecimal; } wsTarget = wbTarget.Worksheets[0]; var advices2 = EvalueAdviceG2(wsTarget.Cells["AT7"].Value.ToString() , sum3PreviousMonths, actualMonth, lastYearmonth, wsTarget.Cells["E48"].Value.ToString()); wsTarget.Cells["E48"].Value = advices2.Item1; wsTarget.Cells["E51"].Value = advices2.Item2; #endregion #region Graphic 3 wsTarget = wbTarget.Worksheets[2]; lastYearmonth = 0; actualMonth = 0; sum3PreviousMonths = 0; for (var i = 2; i < 15; i++) { dateValue = ParseDateXlsToDateTime(int.Parse(wsSource.Cells[11, i].Value.ToString())); wsTarget.Cells[9, i].Value = FormatMonthYear(dateValue.Value.Month, dateValue.Value.Year, true); // headerDates valueDecimal = 0; range = wsSource.Cells[14, i]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells[10, i].Value = valueDecimal; if (i == 2) { lastYearmonth = valueDecimal; } else if (i == 14) { actualMonth = valueDecimal; } else if (i >= 11 && i < 14) { sum3PreviousMonths += valueDecimal; // sum of 3 previous months } valueDecimal = 0; range = wsSource.Cells[15, i]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells[11, i].Value = valueDecimal; } wsTarget = wbTarget.Worksheets[0]; var advices3 = EvalueAdviceG3(wsTarget.Cells["AT7"].Value.ToString() , sum3PreviousMonths, actualMonth, lastYearmonth, wsTarget.Cells["AD48"].Value.ToString()); wsTarget.Cells["AD48"].Value = advices3.Item1; wsTarget.Cells["AD51"].Value = advices3.Item2; #endregion #region Graphic 4 index = 1; for (var i = 19; i < 24; i++, index++) { range = wsSource.Cells[19, 2]; int.TryParse(range.Value.ToString(), out valueInt); wsTarget.Cells["E59"].Value = valueInt.ToString(); range = wsSource.Cells[19, 3]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells["H59"].Value = $"({(int)(valueDecimal * 100)}%)"; range = wsSource.Cells[20, 2]; int.TryParse(range.Value.ToString(), out valueInt); wsTarget.Cells["E61"].Value = valueInt.ToString(); range = wsSource.Cells[20, 3]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells["H61"].Value = $"({(int)(valueDecimal * 100)}%)"; range = wsSource.Cells[21, 2]; int.TryParse(range.Value.ToString(), out valueInt); wsTarget.Cells["E63"].Value = valueInt.ToString(); range = wsSource.Cells[21, 3]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells["H63"].Value = $"({(int)(valueDecimal * 100)}%)"; range = wsSource.Cells[22, 2]; int.TryParse(range.Value.ToString(), out valueInt); wsTarget.Cells["E65"].Value = valueInt.ToString(); range = wsSource.Cells[22, 3]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells["H65"].Value = $"({(int)(valueDecimal * 100)}%)"; range = wsSource.Cells[23, 2]; int.TryParse(range.Value.ToString(), out valueInt); wsTarget.Cells["E67"].Value = valueInt.ToString(); range = wsSource.Cells[23, 3]; decimal.TryParse(range.Value.ToString(), out valueDecimal); wsTarget.Cells["H67"].Value = $"({(int)(valueDecimal * 100)}%)"; } wsTarget = wbTarget.Worksheets[0]; #endregion #region Graphic 5 wsTarget = wbTarget.Worksheets[2]; wbSource.WorkbookSet.Calculate(); List <(int, int)> mayor_days = new List <(int, int)>(); index = 7; // Begins on Sunday int lessValueIndex = 0; for (var i = 2; i < 9; i++, index--) { lessValueIndex = -1; valueInt = 0; int.TryParse(wsSource.Cells[33, i].Value.ToString(), out valueInt); wsTarget.Cells[15, i].Value = valueInt; if (valueInt > 0) { if (mayor_days.Count == 0) { mayor_days.Add((index, valueInt)); } else { if (mayor_days.Count < 3) { mayor_days.Add(ValueTuple.Create(index, valueInt)); } else { for (var pos = 0; pos < mayor_days.Count; pos++) { if (valueInt > mayor_days[pos].Item2) { lessValueIndex = pos; } } if (lessValueIndex != -1) { mayor_days[lessValueIndex] = (index, valueInt); } } } } } wsTarget = wbTarget.Worksheets[0]; var advices5 = EvalueAdviceG5(mayor_days, wsTarget.Cells["AD70"].Value.ToString()); wsTarget.Cells["AD70"].Value = advices5.Item1; #endregion string nameTarget = $"{name}~{ruc}~{email}.xlsx"; using (MemoryStream file = new MemoryStream()) { wbTarget.SaveToStream(file, SpreadsheetGear.FileFormat.OpenXMLWorkbook); wbTarget.SaveAs($@"{FolderPath}\{nameTarget}", SpreadsheetGear.FileFormat.OpenXMLWorkbook); GeneratePDF(file, $@"{FolderPath}\{nameTarget}", ruc.Trim()); } counterWorked++; this.ProgressFinished = counterWorked; } this.ProgressFinished = counterWorked; this.WorkFinished = true; }
private static void ReadXlsxFileIntoList() { Console.WriteLine("ProcessInputXlsxFile".PadRight(30, '.') + "ReadXLSXFileIntoList() -- started"); StaticVariable.ConsoleOutput.Add("ProcessInputXlsxFile".PadRight(30, '.') + "ReadXLSXFileIntoList() -- started"); StaticVariable.ProgressDetails.Add(Environment.NewLine + "ProcessInputXlsxFile::ReadXLSXFileIntoList()"); StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + "Any line containing 'DefaultXX' will be ignored, as will all headers"); string[] worksheetsTypes = { Constants.Duration, Constants.Capped, Constants.Pulse }; List <string> workSheetsNotUsed = new List <string>(); List <string> discardedLines = new List <string>(); List <string> workSheetsUsed = new List <string>(); SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(StaticVariable.InputFile); foreach (string wksheet in worksheetsTypes) { try { SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[wksheet]; SpreadsheetGear.IRange cells = worksheet.Cells; workSheetsUsed.Add(wksheet); } catch (Exception) { workSheetsNotUsed.Add(wksheet); } } foreach (string wksheet in workSheetsUsed) { SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[wksheet]; SpreadsheetGear.IRange cells = worksheet.Cells; var currentColumn = 0; for (currentColumn = 0; currentColumn < cells.ColumnCount; currentColumn++) { if (cells[0, currentColumn].Text.ToUpper().Equals(Constants.FinalColumnName)) { currentColumn++; break; } } var maximumNumberOfColumns = currentColumn; try { foreach (SpreadsheetGear.IRange row in worksheet.UsedRange.Rows) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maximumNumberOfColumns; i++) { sb.Append(row[0, i].Value + "\t"); //0.0400 being chopped to 0.04. } string sAdjustSb = sb.ToString().TrimEnd('\t'); if (sAdjustSb.Contains(";") && !DiscardHeaderLine(sAdjustSb)) { discardedLines.Add("- " + sAdjustSb.Substring(0, sAdjustSb.IndexOf('\t'))); } else if (!string.IsNullOrEmpty(sAdjustSb) && !DiscardHeaderLine(sAdjustSb)) { ValidateData.CheckForCommasInLine(sAdjustSb); StaticVariable.InputXlsxFileDetails.Add(ValidateData.CapitaliseWord(sAdjustSb)); } } } catch (Exception e) { StaticVariable.ProgressDetails.Add(Environment.NewLine + "ProcessInputXlsxFile::ReadXLSXFileIntoList()"); StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + "Error in reading in XLSX line into list. Is there any data? "); StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + e.Message); } } workbook.Close(); if (workSheetsNotUsed.Any()) { StaticVariable.ProgressDetails.Add(Environment.NewLine + "ProcessInputXlsxFile::ReadXLSXFileIntoList()"); foreach (var entry in workSheetsNotUsed) { StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + entry + " rates are not being used. Delete this worksheet"); } } foreach (var entry in workSheetsUsed) { StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + entry + " rates are being used. "); } if (discardedLines.Any()) { StaticVariable.ProgressDetails.Add(Environment.NewLine + "ProcessInputXlsxFile::ReadXLSXFileIntoList()"); StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + "Customer destinations discarded."); discardedLines.Sort(); foreach (var entry in discardedLines) { StaticVariable.ProgressDetails.Add(Constants.FiveSpacesPadding + entry); } } StaticVariable.ProgressDetails.Add(Environment.NewLine + "ProcessInputXlsxFile".PadRight(30, '.') + "ReadXLSXFileIntoList()-- completed"); Console.WriteLine("ProcessInputXlsxFile".PadRight(30, '.') + "ReadXLSXFileIntoList() -- finished"); StaticVariable.ConsoleOutput.Add("ProcessInputXlsxFile".PadRight(30, '.') + "ReadXLSXFileIntoList() -- finished"); }
private void OutPutExcel_N4Nguphap(DataTable adtData) { string templatePath = Common.GetTemplate("N4Nguphap_テンプレート.xls"); SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(templatePath); try { SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["N4Nguphap"]; SpreadsheetGear.IRange range = null; //tb.Columns.Add("id"); //tb.Columns.Add("maucau"); //tb.Columns.Add("cachchia"); //tb.Columns.Add("ynghia"); //tb.Columns.Add("vidu"); string dataA, dataB, dataC, dataD, dataE; string[] numofLineA, numofLineB, numofLineC, numofLineD, numofLineE; for (int i = 0, addressY = 2, plus = 0; i < adtData.Rows.Count; i++, addressY++, plus = 0) { dataA = adtData.Rows[i]["id"].ToString(); dataB = adtData.Rows[i]["maucau"].ToString(); dataC = adtData.Rows[i]["cachchia"].ToString(); dataD = adtData.Rows[i]["ynghia"].ToString(); dataE = adtData.Rows[i]["vidu"].ToString(); numofLineA = dataA.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); numofLineB = dataB.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); numofLineC = dataC.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); numofLineD = dataD.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); numofLineE = dataE.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); for (int plusP = 0; plusP < numofLineA.Length; plusP++) { range = worksheet.Cells["A" + (addressY + plusP)]; range.Value = numofLineA[plusP]; } for (int plusP = 0; plusP < numofLineB.Length; plusP++) { range = worksheet.Cells["B" + (addressY + plusP)]; range.Value = numofLineB[plusP]; } for (int plusP = 0; plusP < numofLineC.Length; plusP++) { range = worksheet.Cells["C" + (addressY + plusP)]; range.Value = numofLineC[plusP]; } for (int plusP = 0; plusP < numofLineD.Length; plusP++) { range = worksheet.Cells["D" + (addressY + plusP)]; range.Value = numofLineD[plusP]; } for (int plusP = 0; plusP < numofLineE.Length; plusP++) { range = worksheet.Cells["E" + (addressY + plusP)]; range.Value = numofLineE[plusP]; } plus = Math.Max(numofLineA.Length, numofLineB.Length); plus = Math.Max(numofLineC.Length, plus); plus = Math.Max(numofLineD.Length, plus); plus = Math.Max(numofLineE.Length, plus); addressY = addressY + plus - 1; } string outPath = ""; Common.SaveExcelTemplate(workbook, "N4文法", "xls", out outPath); if (File.Exists(outPath)) { System.Diagnostics.Process.Start(outPath); } } catch (Exception) { throw; } finally { workbook.Close(); } }
private void OutPutExcel_2000共通単語(DataTable adtData) { string templatePath = Common.GetTemplate("2000共通単語_テンプレート.xls"); SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(templatePath); try { SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["2000共通単語"]; SpreadsheetGear.IRange range = null; for (int i = 0, addressY = 2; i < adtData.Rows.Count; i++, addressY++) { range = worksheet.Cells["A" + addressY]; range.Value = adtData.Rows[i]["id"]; range = worksheet.Cells["B" + addressY]; range.Value = adtData.Rows[i]["jp"]; if (adtData.Rows[i]["read"].ToString().Length > 0 || adtData.Rows[i]["tooltipText"].ToString().Length > 0) { range.AddComment(adtData.Rows[i]["read"].ToString().Length > 0 ? (adtData.Rows[i]["read"].ToString() + Environment.NewLine + adtData.Rows[i]["tooltipText"].ToString()) : adtData.Rows[i]["tooltipText"].ToString()); SpreadsheetGear.IComment icomment = range.Comment; using (Graphics g = this.CreateGraphics()) { string item = icomment.ToString(); SizeF sizeF = g.MeasureString(item, Font); icomment.Shape.Width = sizeF.Width; icomment.Shape.Height = sizeF.Height; } } range = worksheet.Cells["C" + addressY]; range.Value = adtData.Rows[i]["read"]; range.WrapText = false; range = worksheet.Cells["D" + addressY]; range.Value = adtData.Rows[i]["vi"]; range.WrapText = false; range = worksheet.Cells["E" + addressY]; range.Value = adtData.Rows[i]["innerText"]; range.WrapText = false; range = worksheet.Cells["F" + addressY]; range.Value = adtData.Rows[i]["outerHtml"]; range.WrapText = false; range = worksheet.Cells["G" + addressY]; range.Value = adtData.Rows[i]["tooltipText"]; range.WrapText = false; } string outPath = ""; Common.SaveExcelTemplate(workbook, "2000共通単語", "xls", out outPath); if (File.Exists(outPath)) { System.Diagnostics.Process.Start(outPath); } } catch (Exception) { throw; } finally { workbook.Close(); } }