public void CreateXlsDoc() { ExcelHandler excelHndlr = new ExcelHandler(); string codeBase = AppContext.BaseDirectory; int fileName = 0; string outputFile; do { outputFile = Path.Combine(codeBase, $"{fileName++}.xlsx"); } while (File.Exists(outputFile)); const int ASCII_ALPHAS_OFFSET = 65; string[,] data = new string[10, 16]; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { data[i, j] = Convert.ToChar(ASCII_ALPHAS_OFFSET + j).ToString(); } } excelHndlr.CreateXlsDoc(outputFile, $"A{2}", $"P{10}", data); }
public void WriteExcelTest() { var eh = new ExcelHandler(this._testCaseList); eh.WriteExcel(); Assert.AreEqual(0,0); }
private static void CompareLinks() { string fileName = ExcelHandler.GetLastFileName(_options.FolderPath, _options.Name + "AllLinksTable*.xlsx"); if (!string.IsNullOrEmpty(fileName)) { Dictionary <string, Object> lastParseLinks = ExcelHandler.LoadFileToDictionary(_options.FolderPath + "\\" + fileName); if (lastParseLinks != null) { Dictionary <string, string> differentLinksMap = new Dictionary <string, string>(); foreach (var lastTimeVistLink in lastParseLinks.Keys) { if (!string.IsNullOrEmpty(lastTimeVistLink) && !pageVisitedURLMapping.ContainsKey(new Uri(lastTimeVistLink))) { differentLinksMap.Add(lastTimeVistLink, "Last Time has link"); } } foreach (var thisTimeVistLink in pageVisitedURLMapping.Keys) { if (!lastParseLinks.ContainsKey(thisTimeVistLink.ToString())) { differentLinksMap.Add(thisTimeVistLink.ToString(), "This Time has link"); } } ExcelHandler.DataTableToExcel(_options.FolderPath + "\\" + _options.Name + "Different" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx", ExcelHandler.DictToDatatTable(differentLinksMap), "Sheet1"); } } }
public async Task <List <Organization> > UploadFilePost() { var files = _accessor.HttpContext.Request.Form.Files; //获取上传对象 var file = files.First(); //判断是否选择文件 if (file == null) { throw new UserFriendlyException(L("File_Empty_Error")); } //判断文件大小(单位:字节) if (file.Length > 10485760) //10MB = 1024 * 1024 *10 { throw new UserFriendlyException(L("File_SizeLimit_Error")); } //将文件流转为二进制数据 byte[] fileBytes; using (var stream = file.OpenReadStream()) { var result = ExcelHandler.ReadExcel <Organization>(stream); foreach (var item in result) { _reposity.Insert(item); } return(await Task.FromResult(result)); } }
private void tsmiOpen_Click(object sender, EventArgs e) { this.tbControl.TabPages.Clear(); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Excel file (*.xlsx)|*.xls;*.xlsx"; dialog.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;//Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); dialog.Title = "请选择规范的数据文件"; if (dialog.ShowDialog() == DialogResult.OK) { ExcelHandler excelHandler = new ExcelHandler(dialog.FileName); MapData = excelHandler.ExcelToTable(); foreach (KeyValuePair <string, DataTable> kv in MapData) { this.tbControl.TabPages.Add(kv.Key, kv.Key); TableLayoutPanel tb1 = new TableLayoutPanel(); this.tbControl.TabPages[kv.Key].Controls.Add(tb1); tb1.Dock = DockStyle.Fill; DataGridView grdUpload = new DataGridView(); grdUpload.DataSource = kv.Value; grdUpload.Dock = DockStyle.Fill; tb1.Controls.Add(grdUpload, 0, 0); grdUpload.ReadOnly = true; } } }
private FileResult ToFileResult(AbstractDataGrid abstractFile, string format) { // Get abstract grid FileHandlerBase handler; string contentType; if (format == FileFormats.Xlsx) { handler = new ExcelHandler(_localizer); contentType = MimeTypes.Xlsx; } else if (format == FileFormats.Csv) { handler = new CsvHandler(_localizer); contentType = MimeTypes.Csv; } else { throw new FormatException(_localizer["Error_UnknownFileFormat"]); } var fileStream = handler.ToFileStream(abstractFile); return(File(((MemoryStream)fileStream).ToArray(), contentType)); }
public async Task <IActionResult> Import(IFormFile file) { if (file == null) { return(Content("Error: File is null")); } string fileExtension = Path.GetExtension(file.FileName); if (fileExtension != ".xls" && fileExtension != ".xlsx") { return(Content("Error: Wrong file extension")); } var stream = file.OpenReadStream(); List <Contract> contracts = await Task.Run(() => { ExcelHandler excelHandler = new ExcelHandler(stream, fileExtension); return(excelHandler.GetContractsFromExcel()); }); DBContext dBContext = new DBContext(); await dBContext.Contracts.AddRangeAsync(contracts); await dBContext.SaveChangesAsync(); return(Content("All good")); }
protected virtual AbstractDataGrid FileToAbstractGrid(IFormFile file, ParseArguments args) { // Determine an appropriate file handler based on the file metadata FileHandlerBase handler; if (file.ContentType == "text/csv" || file.FileName.EndsWith(".csv")) { handler = new CsvHandler(_localizer); } else if (file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || file.FileName.EndsWith(".xlsx")) { handler = new ExcelHandler(_localizer); } else { throw new FormatException(_localizer["Error_UnknownFileFormat"]); } using (var fileStream = file.OpenReadStream()) { // Use the handler to unpack the file into an abstract grid and return it AbstractDataGrid abstractGrid = handler.ToAbstractGrid(fileStream); return(abstractGrid); } }
public void OnOk(Window win) { if (this.CurrentViewModel is GoogleHistoryViewModel) { GoogleHistoryViewModel gh = this.CurrentViewModel as GoogleHistoryViewModel; this.m_history = gh.Adapt <GoogleHistory>(); this.m_history.OnRetrievedDataHandler = History_OnRetrievedData; this.m_history.ExecuteAsync(); this.CurrentViewModel = new LoadingViewModel(); this.IsOkButtonVisible = false; this.RaisePropertyChanged(null); } else if (this.CurrentViewModel is LoadingViewModel) { } else if (this.CurrentViewModel is DataResultViewModel) { this.OnCancel(win); DataResultViewModel dvm = this.CurrentViewModel as DataResultViewModel; if (ExcelHandler.WriteToRangeHandler != null) { ExcelHandler.WriteToRangeHandler(dvm.Result, dvm.GH); } } }
// Maybe we should move these to ControllerUtilities protected FileResult AbstractGridToFileResult(AbstractDataGrid abstractFile, string format) { // Get abstract grid FileHandlerBase handler; string contentType; if (format == FileFormats.Xlsx) { handler = new ExcelHandler(_localizer); contentType = MimeTypes.Xlsx; } else if (format == FileFormats.Csv) { handler = new CsvHandler(_localizer); contentType = MimeTypes.Csv; } else { throw new FormatException(_localizer["Error_UnknownFileFormat"]); } var fileStream = handler.ToFileStream(abstractFile); fileStream.Seek(0, System.IO.SeekOrigin.Begin); return(File(fileStream, contentType)); }
private void SaveFileByDialog(object fileObj) { if (fileObj is string fileDir && fileDir.EndsWith("xml")) { if (_tcDic.First().Value == null) { return; } SaveFileDialog sfd = new SaveFileDialog { RestoreDirectory = true, Filter = "Excel 2007(*.xlsx)|*.xlsx|Excel 2003(*.xls)|*.xls" }; ExcelHandler eh = new ExcelHandler(_tcDic.First().Value); if (sfd.ShowDialog() == DialogResult.OK) { try { eh.WriteExcel(sfd.FileName); } catch (Exception ex) { OutputDisplay.ShowMessage(ex.ToString(), Color.Red); this._logger.Error(ex); return; } } }
// GET: /<controller>/ public IActionResult SaveCustomeFilter(Dictionary <string, string> cond) { ExcelHandler xlsHandler = new ExcelHandler(); xlsHandler.DownloadXLS(); return(Ok("Ну я отработал...")); }
private static void Finish() { CompareLinks(); ExcelHandler.DataTableToExcel(_options.FolderPath + "\\" + _options.Name + "AllLinksTable" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx", ExcelHandler.LinkToDatatTable(pageVisitedURLMapping), "Sheet1"); ExcelHandler.DataTableToExcel(_options.FolderPath + "\\PageNonValidateList.xlsx", ExcelHandler.ConvertClassToTable(pageNotFoundMapping)); SaveSitemap(); _watch.Stop(); logger.Info(_options.Name + " Finish all task in {0}", _watch.Elapsed); }
public ActionResult Index(HttpPostedFileBase file, UploadedFileInfo upload) { //check file extension string extension = Path.GetExtension(Request.Files[0].FileName).ToLower(); if (extension != ".xls" && extension != ".xlsx") { ModelState.AddModelError("uploadError", "Supported file extensions: .xls, .xlsx"); return(View()); } // extract only the filename var fileName = Path.GetFileName(file.FileName); //display adding date var currentDate = DateTime.Now.ToString("d"); // store the file inside ~/App_Data/uploads folder var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), currentDate + fileName); using (AccountingContext context = new AccountingContext()) { // Verify that the user selects a file if (file != null && file.ContentLength > 0) { file.SaveAs(path); // save the filename and path in UploadedFilesInfo table upload.FileName = fileName; upload.FilePath = path; context.UploadedFiles.Add(upload); context.SaveChanges(); } else { ModelState.AddModelError("blankFileError", "You're trying to attach blank file."); return(View()); } ExcelHandler excelHandler = new ExcelHandler(); FileInfo fi1 = new FileInfo(path); var queryId = from customer in context.UploadedFiles select customer.UploadedFileInfoId; int?currentId = queryId.ToList().Last(); var id = currentId++ ?? 1; excelHandler.SelectDataFromFile(fi1, id); } // redirect back to the index action to show the form once again return(RedirectToAction("Index")); }
void UCDictionaryAddOrEdit_ExportEvent(object sender, EventArgs e) { try { string dir = Application.StartupPath + @"\ExportFile"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = dir; sfd.Title = "导出文件"; sfd.DefaultExt = "xls"; sfd.Filter = "Microsoft Office Excel 文件(*.xls;*.xlsx)|*.xls;*.xlsx|Microsoft Office Excel 文件(*.xls)|*.xls|Microsoft Office Excel 文件(*.xlsx)|*.xlsx"; sfd.FileName = dir + @"\字典码表" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; DialogResult result = sfd.ShowDialog(); if (result == DialogResult.OK) { int totalCount = 0; PercentProcessOperator process = new PercentProcessOperator(); #region 匿名方法,后台线程执行完调用 process.BackgroundWork = delegate(Action <int> percent) { DataTable dt = DBHelper.GetTable("查询码表", "v_dictionaries", "*", where, "", "order by dic_code"); totalCount = dt.Rows.Count; dt = ExcelHandler.HandleDataTableForExcel(dt, dgvDicList); ExcelHandler.ExportDTtoExcel(dt, "", sfd.FileName, percent); }; #endregion process.MessageInfo = "正在执行中"; process.Maximum = totalCount; #region 匿名方法,后台线程执行完调用 process.BackgroundWorkerCompleted += new EventHandler <BackgroundWorkerEventArgs>( delegate(object osender, BackgroundWorkerEventArgs be) { if (be.BackGroundException == null) { MessageBoxEx.ShowInformation("导出成功!"); } else { Utility.Log.Log.writeLineToLog("【字典码表】" + be.BackGroundException.Message, "client"); MessageBoxEx.ShowWarning("导出出现异常"); } } ); #endregion process.Start(); } } catch (Exception ex) { Utility.Log.Log.writeLineToLog("【字典码表】" + ex.Message, "client"); MessageBoxEx.ShowWarning("导出失败!"); } }
public static void Task6() { SQLiteHandler.TransferSQLiteData(); var excelHandler = new ExcelHandler(); var context = new ComputersFactoryContext(); var mySqlHandler = new MySQLHandler(context); var excelExporter = new ExcelExporter(excelHandler, mySqlHandler); excelExporter.GenerateReport("../../../Excel-Reports/Reports.xlsx"); }
public async Task <IActionResult> OnGetÜberzeitkontrolleAsync() { UserModel user = _db.User.Where(u => u.ID == new Guid(User.FindFirst(ClaimTypes.NameIdentifier).Value)).FirstOrDefault(); var filename = @"Überzeitkontrolle_" + user.Department + ".xlsx"; await ExcelHandler.CreateÜberzeitkontrolle(user.Department, _db); return(File(System.IO.File.ReadAllBytes(@"C:\temp\" + filename), "application/vnd.ms-excel", filename)); }
private void button9_Click(object sender, RoutedEventArgs e) { SQLiteHandler.TransferSQLiteData(); var excelHandler = new ExcelHandler(); var context = new ComputersFactoryContext(); var mySqlHandler = new MySQLHandler(context); var excelExporter = new ExcelExporter(excelHandler, mySqlHandler); excelExporter.GenerateReport("../../../Excel-Reports/Reports.xlsx"); }
private void btSensor_Click(object sender, EventArgs e) { string[] parametros = GetListaParametros(); List <string[]> listaMin = new List <string[]>(); List <string[]> listaMax = new List <string[]>(); List <string[]> listaAvg = new List <string[]>(); if (rbSensor1.Checked) { ExcelHandler.CreateNewExcelFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx"); foreach (string parametro in parametros) { listaMin.Add(serv.getParameterMinHourInDay(parametro, dateToStr(dtSensor1.Text))); listaMax.Add(serv.getParameterMaxHourInDay(parametro, dateToStr(dtSensor1.Text))); listaAvg.Add(serv.getParameterAvgHourInDay(parametro, dateToStr(dtSensor1.Text))); } ExcelHandler.WriteToExcelFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx", listaMin, listaMax, listaAvg, parametros); } else if (rbSensor2.Checked) { //fazer uma verificação se o valor da caixa está entre 1 e 52 if ((lbWeek.Value > 0) && (lbWeek.Value < 53)) { ExcelHandler.CreateNewExcelFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx"); foreach (string parametro in parametros) { int auxSemana = Decimal.ToInt32(lbWeek.Value); listaMin.Add(serv.getParameterMinWeekly(parametro, auxSemana)); listaMax.Add(serv.getParameterMaxWeekly(parametro, auxSemana)); listaAvg.Add(serv.getParameterAvgWeekly(parametro, auxSemana)); } ExcelHandler.WriteToExcelFileWeek(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx", listaMin, listaMax, listaAvg, parametros); } else { MessageBox.Show("Week number out of range [1-52]"); } } else if (rbSensor3.Checked) { ExcelHandler.CreateNewExcelFile(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx"); foreach (string parametro in parametros) { listaMin.Add(serv.getParameterMinRangeDay(parametro, dateToStr(dtSensor1.Text), dateToStr(dtSensor2.Text))); listaMax.Add(serv.getParameterMaxRangeDay(parametro, dateToStr(dtSensor1.Text), dateToStr(dtSensor2.Text))); listaAvg.Add(serv.getParameterAvgRangeDay(parametro, dateToStr(dtSensor1.Text), dateToStr(dtSensor2.Text))); } ExcelHandler.WriteToExcelFileRangeDays(AppDomain.CurrentDomain.BaseDirectory.ToString() + "App_data\\SensorGrafico.xlsx", listaMin, listaMax, listaAvg, parametros); } }
private void InitCoreLogic() { htmlHandler = new HtmlHandler(); xlsHanlder = new ExcelHandler(); //TODO: Remove in production. if (Debugger.IsAttached) { txtBoxToInputExcel.Text = @"C:\Users\artemm\Desktop\EmployeeInfoGrabber\InfoGrabber\bin\Debug\Resources\Input\input.xlsx"; txtBoxToHtmlReport.Text = @"C:\Users\artemm\Desktop\EmployeeInfoGrabber\InfoGrabber\bin\Debug\Resources\Output"; } }
public void Main(string file) { var wordHandler = new WordHandler(); var pdfHandler = new PdfHandler(); var excelHandler = new ExcelHandler(); wordHandler.SetSuccessor(pdfHandler); pdfHandler.SetSuccessor(excelHandler); wordHandler.Process(file); }
public static async Task <DataTable> ParseMultipartAsync(this HttpContent postedContent) { ExcelHandler excelHandler = new ExcelHandler(); var provider = await postedContent.ReadAsMultipartAsync(); string worksheetName = "Sheet1"; string cellName = "B2"; var files = new Dictionary <string, HttpPostedFile>(StringComparer.InvariantCultureIgnoreCase); var fields = new Dictionary <string, HttpPostedField>(StringComparer.InvariantCultureIgnoreCase); var ExcelData = new Dictionary <string, string>(); DataTable table = new DataTable(); foreach (var content in provider.Contents) { var fieldName = content.Headers.ContentDisposition.Name.Trim('"'); if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName)) { var file = await content.ReadAsByteArrayAsync(); //MatchRes = FingerprintMatcher.MatchPrintInnovatrics(file); var fileName = content.Headers.ContentDisposition.FileName.Trim('"'); string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Xlxs_Files"); CreateFolder(folderPath); using (FileStream fileStream = new FileStream(Path.Combine(folderPath, fileName), FileMode.OpenOrCreate)) { fileStream.Write(file, 0, file.Length); fileStream.Close(); } files.Add(fieldName, new HttpPostedFile(fieldName, fileName, file)); if (fileName.EndsWith(".xlsx") || (fileName.EndsWith(".xls"))) { excelHandler.Extention = "true"; //ExcelData = ExcelHandler.GetDefinedNames(Path.Combine(folderPath, fileName)); table = excelHandler.ImportExcel(Path.Combine(folderPath, fileName)); //excelHandler.CreateSpreadsheetWorkbook(Path.Combine(folderPath, fileName)); } else { var data = await content.ReadAsStringAsync(); fields.Add(fieldName, new HttpPostedField(fieldName, data)); } } return(table); } return(table); }
/// <summary> 在线用户 /// </summary> void UCOnLineUser_ExportEvent(object sender, EventArgs e) { try { string fileName = "在线用户" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; ExcelHandler.ExportExcel(fileName, dgvUser); } catch (Exception ex) { GlobalStaticObj_Server.GlobalLogService.WriteLog("在线用户", ex); MessageBoxEx.ShowWarning("程序异常"); } }
//导出 private void btnOutput_Click(object sender, EventArgs e) { try { string fileName = "组织管理" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; ExcelHandler.ExportExcel(fileName, dgvRecord); } catch (Exception ex) { GlobalStaticObj_Server.GlobalLogService.WriteLog("组织管理", ex); MessageBoxEx.ShowWarning("程序异常"); } }
/// <summary> /// 导出事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void UCSupplierManager_ExportEvent(object sender, EventArgs e) { try { string fileName = "供应商档案" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; ExcelHandler.ExportExcel(fileName, dgvSupplierList); } catch (Exception ex) { Utility.Log.Log.writeLineToLog("【供应商档案】" + ex.Message, "server"); MessageBoxEx.ShowWarning("导出失败!"); } }
static void Main(string[] args) { XMLReader config = new XMLReader(XMLConfigPath, new XmlDocument()); string[] paths = config.Read(); TXTReader txt = new TXTReader(paths[0]); ExcelHandler ex = new ExcelHandler(paths[1], new Application()); ChromeHandler ch = new ChromeHandler(new ChromeDriver()); Extractor ext = new Extractor(txt.Read()); ext.ExtractData(ex, ch); }
private void btnExport_Click(object sender, EventArgs e) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Filter = "Excel file (*.xlsx)|*.xls;*.xlsx"; saveDialog.FileName = this.chartType + DateTime.Now.ToShortDateString(); saveDialog.AddExtension = true; if (saveDialog.ShowDialog() == DialogResult.OK) { ExcelHandler er = new ExcelHandler(saveDialog.FileName); er.TableToExcel(this.dgvControlData.DataSource as DataTable, pBox.Image); MessageBox.Show(saveDialog.FileName, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public HomeController(Helpers helpers, RdotNetConnector r, IOptions <AirtableConfiguration> airtableConfig, IOptions <TwitterConfiguration> twitterConfig, GoogleSheetsConnector gSC, EmailHelper emailHelper, ExcelHandler excelHandler, PythonConnector pythonConnector, DataTabler dataTabler, CsvHandler csvHandler, CbsTransactionTrendsController cbsTrendsController) { _helpers = helpers; _r = r; _airtableConfig = airtableConfig.Value; _twitterConfiguration = twitterConfig.Value; _gSC = gSC; _emailHelper = emailHelper; _excelHander = excelHandler; _pythonConnector = pythonConnector; _dataTabler = dataTabler; _csvHandler = csvHandler; _cbsTrendsController = cbsTrendsController; // this._cbsTrendsController = cbsTrendsController; }
/// <summary> /// 导出事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void UC_ExportEvent(object sender, EventArgs e) { if (this.dgvRData.Rows.Count == 0) { return; } try { string fileName = "维修结算单" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; ExcelHandler.ExportExcel(fileName, dgvRData); } catch (Exception ex) { Utility.Log.Log.writeLineToLog("【维修结算单】" + ex.Message, "server"); MessageBoxEx.ShowWarning("导出失败!"); } }
/// <summary> 导出 /// </summary> void UCDictionaryManager_ExportEvent(object sender, EventArgs e) { try { //获取数据表 DataTable dt = DBHelper.GetTable("查询码表", "v_dictionaries", "*", where, "", "order by dic_code"); //根据datagridview列制定datatable导出列及列名称 dt = ExcelHandler.HandleDataTableForExcel(dt, dgvDicList); string fileName = "字典码表" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; ExcelHandler.ExportExcel(fileName, dt); } catch (Exception ex) { Utility.Log.Log.writeLineToLog("【字典码表】" + ex.Message, "client"); MessageBoxEx.ShowWarning("导出失败!"); } }