private void efBtn_excel_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = "c:\\"; openFileDialog.Filter = "txt files (*.xls)|*.xls"; openFileDialog.FilterIndex = 2; openFileDialog.Multiselect = false; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { efGroupBox3.Controls.Clear(); m_workbookView = new WorkbookView(); m_workbookView.GetLock(); efGroupBox3.Controls.Add(m_workbookView); m_workbookView.Parent = efGroupBox3; m_workbookView.Dock = DockStyle.Fill; SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(openFileDialog.FileName, System.Globalization.CultureInfo.CurrentCulture); m_workbookView.ActiveWorkbook = workbook; m_workbookView.ReleaseLock(); } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
private static SpreadsheetGearSeries GetSimpleSeries(string filename) { SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(filename); string sheetName = workbook.Sheets[0].Name; SpreadsheetGearSeries s = new SpreadsheetGearSeries(workbook, sheetName, "A", "B", "cfs"); return(s); }
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 static void SaveExcelTemplate(SpreadsheetGear.IWorkbook workbook, string fileName, string fileType, out string outPath) { string path; if (fileType == "xlsx") { path = Path.Combine(Path.GetTempPath(), fileName + DateTime.Now.ToString("yyMMdd_hhmmss") + ".xlsx"); workbook.SaveAs(path, SpreadsheetGear.FileFormat.OpenXMLWorkbook); } else { path = Path.Combine(Path.GetTempPath(), fileName + DateTime.Now.ToString("yyMMdd_hhmmss") + ".xls"); workbook.SaveAs(path, SpreadsheetGear.FileFormat.Excel8); } outPath = path; }
protected void _btnExportarExcel_Click(object sender, EventArgs e) { List <List <string> > contenido = new List <List <string> >(); List <string> fila = new List <string>(); string[] badChars = { "á", "é", "í", "ó", "ú", "ñ" }; string[] goodChars = { "á", "é", "í", "ó", "ú", "ñ" }; foreach (GridViewRow r in _gvwEventos.Rows) { for (int i = 0; i < r.Cells.Count; i++) { string text = r.Cells[i].Text; for (int k = 0; k < badChars.Length; k++) // Limpiar caracteres { text = text.Replace(badChars[k], goodChars[k]); // Quitar tildes u caracteres especiales del nombre } fila.Add(text); } contenido.Add(fila); fila = new List <string>(); } ReporteExcel report = new ReporteExcel(); SpreadsheetGear.IWorkbook workbook = report.generarReporte("Bitacora " + _txtFechaConsulta.Text.Replace('/', '-'), new List <string> { "Fecha", "Operador", "Evento" }, contenido); Thread STAThread = new Thread(() => { // Stream the Excel spreadsheet to the client in a format // compatible with Excel 97/2000/XP/2003/2007/2010. Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=" + "Bitacora " + _txtFechaConsulta.Text + ".xls"); workbook.SaveToStream(Response.OutputStream, SpreadsheetGear.FileFormat.Excel8); Response.End(); }); STAThread.SetApartmentState(ApartmentState.STA); STAThread.Start(); STAThread.Join(); }
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(); } }
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); }
// 导出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> /// Método que se encarga de cargar una imagen en memoria cargada en el componente Input para carga de archivos /// </summary> /// <returns>Retorna uan arreglo de bytes con la imagen</returns> protected void _btnConsultar_Click(object sender, EventArgs e) { Usuario user = null; int contador = 0; _controladorSGC = new ControladorSGC(); _imgMensajeBusqueda.Visible = false; _lblMensajeBusqueda.Visible = false; _sesion = new Sesion(); _cookieActual = _sesion.verificarValidez(Request.Cookies["PS"]); if (_cookieActual == null) // Si la cookie expira redirecciona a la pantalla de Login { Response.Redirect("../Autentificacion/Login.aspx"); } else // Volver a crear la cookie en el cliente, con el nuevo tiempo de expiración { Response.SetCookie(_cookieActual); } // Verificar que se haya selecionado un criterio de búsqueda if (_ddlCriterio.SelectedIndex == 0) { // _imgMensajeBusqueda.ImageUrl = "../Imagenes/Advertencia.png"; _lblMensajeBusqueda.Text = "Debe seleccionar un criterio de búsqueda"; _imgMensajeBusqueda.Visible = true; _lblMensajeBusqueda.Visible = true; return; } if (_ddlCriterio.SelectedIndex == 3) //si el criterio seleccionado es por rango de fechas { // Verificar que los campos de la busqueda estén llenos if ((_txtValor2.Text.Equals("")) || (_txtValor3.Text.Equals(""))) { _imgMensajeBusqueda.ImageUrl = "../Imagenes/Advertencia.png"; _lblMensajeBusqueda.Text = "Debe ingresar fechas para la busqueda"; _imgMensajeBusqueda.Visible = true; _lblMensajeBusqueda.Visible = true; return; } else { DateTime fechaInicial = DateTime.ParseExact(_txtValor2.Text, "dd/MM/yyyy", null); DateTime fechaFinal = DateTime.ParseExact(_txtValor3.Text, "dd/MM/yyyy", null); try { List <List <string> > contenido = _controladorSGC.crearArchivoUsuariosPorFecha(fechaInicial, fechaFinal); string nombreArchivo = "Cuentas entre " + fechaInicial.Date.Day.ToString() + "-" + fechaInicial.Month.ToString() + "-" + fechaInicial.Year.ToString() + " y " + fechaFinal.Day.ToString() + "-" + fechaFinal.Month.ToString() + "-" + fechaFinal.Year.ToString(); ReporteExcel report = new ReporteExcel(); SpreadsheetGear.IWorkbook workbook = report.generarReporte(nombreArchivo, new List <string> { "Login", "Carrera", "Fecha de Creación" }, contenido); Thread STAThread = new Thread(() => { // Stream the Excel spreadsheet to the client in a format // compatible with Excel 97/2000/XP/2003/2007/2010. Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=" + nombreArchivo + ".xls"); workbook.SaveToStream(Response.OutputStream, SpreadsheetGear.FileFormat.Excel8); Response.End(); }); STAThread.SetApartmentState(ApartmentState.STA); STAThread.Start(); STAThread.Join(); } catch (Exception ex) { _imgMensajeBusqueda.ImageUrl = "../Imagenes/Advertencia.png"; _lblMensajeBusqueda.Text = ex.Message; _imgMensajeBusqueda.Visible = true; _lblMensajeBusqueda.Visible = true; } } } else { // Verificar que los campos de la busqueda estén llenos if (_txtValor.Text.Equals("")) { _imgMensajeBusqueda.ImageUrl = "../Imagenes/Advertencia.png"; _lblMensajeBusqueda.Text = "Debe ingresar algún valor para la busqueda"; _imgMensajeBusqueda.Visible = true; _lblMensajeBusqueda.Visible = true; return; } // El criterio seleccionado es "Login" if (_ddlCriterio.SelectedIndex == 1) { user = _controladorSGC.buscarUsuario(_txtValor.Text, true); // Login } if (_ddlCriterio.SelectedIndex == 2) { user = _controladorSGC.buscarUsuario(_txtValor.Text, false); //Carnet _lblUsuario.Visible = true; _txtUsuario.Visible = true; } // Se actualiza el contenido de la interfaz if (user != null) { _txtCarnet.Text = user.Carnet; _txtNombre.Text = user.Nombre; _txtPApellido.Text = user.Apellidos.Split(' ')[0]; _txtSApellido.Text = user.Apellidos.Split(' ')[1]; _txtTelefono.Text = user.TelefonoCasa; _txtCelular.Text = user.TelefonoCelular; _txtCorreo.Text = user.Correo; _txtUsuario.Text = user.UID; foreach (ListItem carrera in _ddlCarrera.Items) { if (carrera.Text == user.Carrera) { _ddlCarrera.SelectedIndex = contador; } else { contador++; } } if (user.Grupo == "Estudiante") { _rblUsarios.SelectedIndex = 0; } else { _rblUsarios.SelectedIndex = 1; } _imgMensajeBusqueda.Visible = false; _lblMensajeBusqueda.Visible = false; _bntModificar.Enabled = true; _lblMensaje.Visible = false; _imgMensaje.Visible = false; _upConsultaUsuario.Update(); } else { _imgMensajeBusqueda.ImageUrl = "../Imagenes/Error.png"; _lblMensajeBusqueda.Text = "Usuario no encontrado"; _imgMensajeBusqueda.Visible = true; _lblMensajeBusqueda.Visible = true; _txtCarnet.Text = ""; _txtNombre.Text = ""; _txtPApellido.Text = ""; _txtSApellido.Text = ""; _txtTelefono.Text = ""; _txtCelular.Text = ""; _txtCorreo.Text = ""; _txtPassword.Text = ""; _txtCPassword.Text = ""; _ddlCarrera.SelectedIndex = 0; //if(_rblUsarios.SelectedItem.Selected) // _rblUsarios.SelectedItem.Selected = false; _bntModificar.Enabled = false; } } }
//end getfromfile /// <summary> /// return datatable of origin names when there is a start range but no end range /// iterate through from start cell and end when an empty cell is reached /// </summary> /// <param name="dir">location of excel worknook</param> /// <param name="comapnygroup">identifies worksheet to use depending on company</param> /// <param name="xlsheet">worksheet to use within workbbok</param> /// <param name="startrange">start cell on worksheet colunm/row value e.g. A1 or A1:A50</param> /// <returns>indexed datatable of items</returns> public static DataTable getfromfile(string dir, string companygroup, string xlsheet, string xlstart) { //***** //100212 check against company id, if no file just use "officepricer" prefix //namecustomcontroller _name = new namecustomcontroller(); //string _cg = _name.get_company_group(companyid); string _source = companygroup != "0" ? get_latest_pricer(dir, companygroup) : get_latest_pricer(dir); //find latest upload of pricer //**** string _copy = companygroup.ToString() + "_" + DateTime.Now.ToString("ddMMyyHHmmss") + ".xls"; fso_copy_file(dir + _source, dir + _copy); SpreadsheetGear.IWorkbook _wb = SpreadsheetGear.Factory.GetWorkbook(HttpContext.Current.Server.MapPath(dir + _copy)); //disable password protection for now _wb.Unprotect("Trueblue"); //is this necessary in web apps - seems primarily for threading in winforms //_wb.WorkbookSet.GetLock(); //acquire lock //get range SpreadsheetGear.IRange _range = _wb.Worksheets[xlsheet].Range[xlstart]; //_range.Replace("", "*", SpreadsheetGear.LookAt.Whole, SpreadsheetGear.SearchOrder.ByColumns, false); DataTable _dt = new DataTable(); //_dt =_range.GetDataTable(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders); //add a datatabe name and a column name so e.g. can data bind to combo _dt.Columns.Add("item_index", typeof(int)); _dt.Columns.Add("item", typeof(string)); _dt.TableName = "item_table"; _dt.PrimaryKey = new DataColumn[] { _dt.Columns["Item_index"] }; //_dt.Columns[0].ColumnName = "item"; Boolean _end = false; int _ix = 0; while (_end == false) { DataRow _dr = _dt.NewRow(); string _s = _range.Rows[_ix, 0].Value != null ? _range.Rows[_ix, 0].Value.ToString() : null; if (!string.IsNullOrEmpty(_s)) { _ix += 1; _dr["item"] = _s; _dr["item_index"] = _ix; _dt.Rows.Add(_dr); } else { _end = true; } } _wb.Protect("Trueblue", true, true); _wb.Close(); //_wb.WorkbookSet.ReleaseLock(); //delete teporary copy fso_kill_file(dir + _copy); return(_dt); }
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(); } }