public void Test_Import_Should_Create_TestExcelObject() { _excelFileMock.Setup(x => x.ConvertToObjects <TestExcelObject>()).Returns(new List <TestExcelObject>()); _excelCreatorMock.Setup(x => x.Create(It.IsAny <FileStream>())).Returns(_excelFileMock.Object); string path = @"fake\path.xlsx"; IEnumerable <TestExcelObject> testExcelObjects = _excelImporter.Import(path); Assert.IsNotNull(testExcelObjects); _excelFileMock.Verify(x => x.ConvertToObjects <TestExcelObject>(), Times.Once); }
public void Imports_data_set_instances_and_annotations() { ExcelImporter importer = new ExcelImporter(new ExcelFactory().GetTestDataFolder()); var dataSet = importer.Import("BurningKnight"); var classes = dataSet.GetInstancesOfType(SnippetType.Class); classes.Count.ShouldBe(79); classes.Count(c => c.Annotations.Count == 3).ShouldBe(79); var functions = dataSet.GetInstancesOfType(SnippetType.Function); functions.Count.ShouldBe(313); functions.Count(c => c.Annotations.Count == 1).ShouldBe(7); functions.Count(c => c.Annotations.Count == 2).ShouldBe(10); functions.Count(c => c.Annotations.Count == 3).ShouldBe(296); var annotators = new List <Annotator>() { new Annotator(1, 6, 1), new Annotator(2, 2, 2), new Annotator(3, 2, 3) }; JoinInstancesAndAnnotators(classes, annotators); var allClassAnnotations = classes.SelectMany(c => c.Annotations); allClassAnnotations.First(a => a.Annotator.Id == 1).Annotator.ShouldBe(annotators.Find(a => a.Id == 1)); allClassAnnotations.First(a => a.Annotator.Id == 2).Annotator.ShouldBe(annotators.Find(a => a.Id == 2)); allClassAnnotations.First(a => a.Annotator.Id == 3).Annotator.ShouldBe(annotators.Find(a => a.Id == 3)); }
private ActionResult Import(int start = 0) { Stopwatch sw = Stopwatch.StartNew(); try { // Seed VISIT records OracleDbHelper.SeedVisitTable(db); // Use ExcelImporter to import CP_ORDER table. var excelImporter = new ExcelImporter(db); excelImporter.Import(start); // Use OracleDbHelper to import all other tables. OracleDbHelper.PopulateDB <CP_VITAL_SIGN>(db); OracleDbHelper.PopulateDB <CP_EXAM>(db); OracleDbHelper.PopulateDB <CP_LAB_TEST>(db); OracleDbHelper.PopulateDB <CP_MEDICAL_DOC>(db); // alone cost: 3.23801252166667 minutes. //return ("Total cost: " + sw.Elapsed.TotalMinutes + "minutes. "); return(RedirectToAction("Index")); } catch (Exception e) { return(RedirectToAction("Error", new{ message = e.Message })); } }
private async void ImportExcelDataIntoDatabase() { try { var message = "The program will read into memory all rows from the spreadsheet, " + "and then process saving them to the database.\n" + "Ready to begin the import process?"; var dr = XtraMessageBox.Show(message, "Begin Import?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dr == DialogResult.No) { return; } var importer = new ExcelImporter(gridViewExcelSource, MappingInfo, Persistent); EventMediator.GetInstance().OnImportStarted(); EventMediator.GetInstance().ImportProgressUpdated += OnProgressUpdated; marquee.Properties.Stopped = false; await importer.Import(); message = "Data has been imported successfully!"; XtraMessageBox.Show(message, "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information); marquee.Properties.Stopped = true; EventMediator.GetInstance().OnImportComplete(); } catch (Exception ex) { ex.Report(); } }
private static async Task <IEnumerable <AdministrativeDistrict> > GetAdministrativeDistrictsAsync(string rootPath) { var file = Path.Combine(rootPath, "Baidu/administrative_districts_and_towns_202003.xlsx"); var importer = new ExcelImporter(); var result = await importer.Import <AdministrativeDistrict>(file); return(result.Data); }
public void ExcelImport(ImportCheckResponse checkResponse) { using (IObjectRepository auditedTdb = DBContext.CreateAuditable(CheckPoint.Instance.UserName, CheckPoint.Instance.HostAddress)) { ExcelImporter importer = new ExcelImporter(auditedTdb); importer.Import(checkResponse); } }
public void Finds_instances_with_all_disagreeing_annotations() { ExcelImporter importer = new ExcelImporter(new ExcelFactory().GetTestDataFolder()); var dataSet = importer.Import("BurningKnight"); var instances = dataSet.GetInstancesWithAllDisagreeingAnnotations(); instances.Count.ShouldBe(21); }
public void Finds_insufficiently_annotated_instances() { ExcelImporter importer = new ExcelImporter(new ExcelFactory().GetTestDataFolder()); var dataSet = importer.Import("BurningKnight"); var instances = dataSet.GetInsufficientlyAnnotatedInstances(); instances.Count.ShouldBe(9); }
public IActionResult ImportData() { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "c.xlsx"); IExcelImporter importer = new ExcelImporter(); var import = importer.Import <StudentImport>(filePath).Result; var data = import.Data; return(Ok()); }
/// <summary> /// 表级别读取 /// 返回结果默认第一个Sheet /// </summary> /// <param name="filePath">保存路径</param> /// <returns></returns> public async Task <ImportResult <T> > ImportAsync <T>(string filePath = "") where T : class, new() { if (!File.Exists(filePath)) { return(null); } var import = await ExcelImporter.Import <T>(filePath); return(import); }
static void Main(string[] args) { IImporter importer; string command; string argument; if (args.Length != 2) { MessageAndExit("Špatný počet parametrů."); } command = args[0]; argument = args[1]; switch (command) { case "import": string extension = Path.GetExtension(argument).ToLower(); if (extension == ".xml") { //primitive form of dependency injection importer = new XMLImporter(new DataConnectorDB()); importer.Import(argument); } else if (extension == ".xls" || extension == ".xlsx") { importer = new ExcelImporter(new DataConnectorDB()); importer.Import(argument); } else { MessageAndExit("Špatný formát souboru (koncovka)."); } break; case "list": DateTime date; bool isDate = DateTime.TryParse(argument, out date); if (!isDate) { MessageAndExit("Špatný formát data (má být RRRR-MM-DD)."); } new DataConnectorDB().OutputList(date); break; default: break; } Console.WriteLine("Hotovo"); Console.WriteLine("Press Any Key To Continue"); Console.ReadLine(); }
public async Task Import_Test() { IExcelImporter Importer = new ExcelImporter(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "Import", "issue236.xlsx"); using (var stream = new FileStream(filePath, FileMode.Open)) { var result = await Importer.Import <Issue236>(stream); Importer.OutputBussinessErrorData <Issue236>(filePath, result.RowErrors.ToList(), out var msg); } }
public async Task Resources_Test() { IExcelImporter Importer = new ExcelImporter(); var exception = await Assert.ThrowsAsync <ArgumentNullException>(async() => { await Importer.Import <Issue236>(filePath: null); }); exception.Message.ShouldContain(Resource.FileNameShouldNotBeEmpty); Resource.Culture = new CultureInfo("en"); Resource.FileNameShouldNotBeEmpty.ShouldBe("The file name cannot be empty!"); Resource.Culture = new CultureInfo("zh-Hans"); Resource.FileNameShouldNotBeEmpty.ShouldBe("文件名不能为空!"); }
/// <summary> /// 导入数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="importer"></param> /// <param name="inputStream"></param> public static async Task <ImportResult <T> > ImportWithErrorCheck <T>(this ExcelImporter importer, Stream inputStream) where T : class, new() { var id = $"{Guid.NewGuid()}.xlsx"; var raw_path = $"temp\\{id}"; var path = Path.Combine(Directory.GetCurrentDirectory(), raw_path); var upload_path = $"{path}.upload"; var datas = new byte[inputStream.Length]; inputStream.Read(datas); using (var f = File.OpenWrite(upload_path)) using (var bw = new BinaryWriter(f)) bw.Write(datas); var import = await importer.Import <T>(upload_path, raw_path); import.CheckError(raw_path); return(import); }
public async Task ExportAndImportUseOneDto_Test() { IExporter exporter = new ExcelExporter(); var filePath = GetTestFilePath($"{nameof(ExportAndImportUseOneDto_Test)}.xlsx"); DeleteFile(filePath); var data = GenFu.GenFu.ListOf <SalaryInfo>(100); data[1].TestDateTimeOffset2 = DateTimeOffset.Now.Date.AddSeconds(123413); data[2].TestDateTimeOffset2 = null; var result = await exporter.Export(filePath, data); result.ShouldNotBeNull(); File.Exists(filePath).ShouldBeTrue(); IImporter Importer = new ExcelImporter(); var importResult = await Importer.Import <SalaryInfo>(filePath); if (importResult.HasError) { _testOutputHelper.WriteLine(importResult.Exception?.ToString()); } importResult.HasError.ShouldBeFalse(); importResult.Data.Count.ShouldBe(data.Count); for (int i = 0; i < importResult.Data.Count; i++) { var item = importResult.Data.ElementAt(i); item.SalaryDate.Date.ShouldBe(data[i].SalaryDate.Date); item.PostSalary = data[i].PostSalary; item.EmpName = data[i].EmpName; item.TestNullDate1.ShouldBe(data[i].TestNullDate1); if (item.TestNullDate2.HasValue) { item.TestNullDate2.Value.Date.ShouldBe(data[i].TestNullDate2.Value.Date); } item.TestDateTimeOffset1.ShouldBe(data[i].TestDateTimeOffset1); item.TestDateTimeOffset2.ShouldBe(data[i].TestDateTimeOffset2); } }
public async Task <List <UpdateCameraDto> > ExcelToUpdateCameraDtoAsync(IFormFile files) { if (files.Length == 0) { return(null); } try { IImporter Importer = new ExcelImporter(); var import9 = await Importer.Import <UpdateCameraDto>(files.OpenReadStream()); var data = import9.Data.ToList(); return(data); } catch (Exception) { return(null); } }
public async Task <PagedResultDto <CameraDto> > PostExcelToCameraInfoAsync(IFormFile files) { if (files.Length == 0) { return(null); } IImporter Importer = new ExcelImporter(); var import9 = Importer.Import <UpdateCameraDto>(files.OpenReadStream()); var data = import9.Result.Data.ToList(); // var data = ExcelHelper.ExcelToDataTable(files.OpenReadStream(), Path.GetExtension(files.FileName), "Sheet", true); PagedSortedRequestDto resultRequestDto = new PagedSortedRequestDto() { MaxResultCount = 200000, SkipCount = 0, Sorting = "Id" }; var cameraData = _cameraAppService.GetListBylike(null, resultRequestDto); var requst = await _cameraAppService.PostInsertList(data); return(requst); }
public async Task <List <CameraDto> > PostExcelToCameraInfoAsync(IFormFile files) { if (files.Length == 0) { return(null); } IImporter Importer = new ExcelImporter(); var import9 = Importer.Import <UpdateCameraDto>(files.OpenReadStream()); var data = import9.Result.Data.ToList(); // var data = ExcelHelper.ExcelToDataTable(files.OpenReadStream(), Path.GetExtension(files.FileName), "Sheet", true); // var list = ListToDataTable.tolist<UpdateCameraDto>(data); List <CameraDto> listcamera = new List <CameraDto>(); foreach (var item in data) { var camera = await _cameraAppService.GetListByCondition(new CameraCondition() { Camera_ID = item.Camera_ID }, null); if (camera.TotalCount == 0) { var Cameradata = await _cameraAppService.CreateAsync(item); listcamera.Add(Cameradata); } } return(listcamera); }
public async Task <ImportResultDto> ImportExcel(ImportExcelInput input) { IExcelImporter Importer = new ExcelImporter(); var stream = new MemoryStream(input.Bytes); var import = await Importer.Import <ArticleImportDto>(stream); var result = new ImportResultDto { HasError = import.HasError, RowErrors = import.RowErrors, TemplateErrors = import.TemplateErrors, }; if (import.RowErrors != null && import.RowErrors.Count > 0) { var newStream = new MemoryStream(stream.ToArray()); Importer.OutputBussinessErrorData <ArticleImportDto>(newStream, import.RowErrors.ToList(), out byte[] fileByte); var createFileOutput = await _fileService.CreateAsync(new CreateFileInput { FileContainerName = FileContainerNameConsts.Temp, FileName = input.FileName, MimeType = input.MimeType, FileType = FileType.RegularFile, ParentId = null, OwnerUserId = CurrentUser.Id, Content = fileByte }); result.ErrorFile = createFileOutput; return(result); } var entitys = ObjectMapper.Map <List <ArticleImportDto>, List <Article> >(import.Data.ToList()); await _repository.InsertManyAsync(entitys); return(result); }
static void Main(string[] args) { string dir = AppDomain.CurrentDomain.BaseDirectory; string templatePath = string.Format(@"{0}{1}", dir, "账目出入.xlsx"); #region 导入测试 ExcelImporter importer = new ExcelImporter(); DataTable dt = null; try { dt = importer.Import(templatePath, "Sheet 1"); } catch (Exception e) { return; } List <Entity> list = new List <Entity>(); Entity entity; foreach (DataRow dr in dt.Rows) { entity = new Entity() { Code = dr.Field <string>("单位编号"), Name = dr.Field <string>("单位名称"), }; string account = dr.Field <string>("应付余额"); decimal Account; decimal.TryParse(account, out Account); entity.Account = Account; list.Add(entity); } #endregion #region 导出测试 //ExcelUtil util = new ExcelUtil(templatePath); //using (ExcelUtil util = new ExcelUtil(templatePath)) //{ // //util.SetCellValue(2, 1, "0810311211"); // //util.SetCellValue(2, 2, "郭坤"); // //util.SetFont("楷体_GB2312", 20, true); // //util.SetCellValue(2, 3, "男"); // //util.SetCellValue(2, 4, 25); // //util.RowAutoFit(2, 4); // //util.ColumnAutoFit(1, 4); // for (int i = 2; i <= 10;i++ ) // { // util.SetCellValue(i, 1, "学号" + (i - 1).ToString()); // util.SetCellValue(i, 2, "姓名" + (i - 1).ToString()); // util.SetCellValue(i, 3, "性别" + (i - 1).ToString()); // util.SetCellValue(i, 4, "年龄" + (i - 1).ToString()); // } // util.SetRange(2, 1, 10, 4); // util.SetAliment(Excel.XlHAlign.xlHAlignCenter, Excel.XlVAlign.xlVAlignCenter); // //util.SetBorders(Excel.XlLineStyle.xlSlantDashDot); // util.SetLeftBorder(Excel.XlLineStyle.xlContinuous); // string exportPath = string.Format(@"{0}{1}", dir, "1.xlsx"); // util.SaveAs(exportPath); //} //using (ExcelExporter util = new ExcelExporter()) //{ // //util.SetCellValue(2, 1, "0810311211"); // //util.SetCellValue(2, 2, "郭坤"); // //util.SetFont("楷体_GB2312", 20, true); // //util.SetCellValue(2, 3, "男"); // //util.SetCellValue(2, 4, 25); // //util.RowAutoFit(2, 4); // //util.ColumnAutoFit(1, 4); // for (int i = 1; i <= 10; i++) // { // util.SetCellValue(i, 1, "学号" + i.ToString()); // util.SetCellValue(i, 2, "姓名" + i.ToString()); // util.SetCellValue(i, 3, "性别" + i.ToString()); // util.SetCellValue(i, 4, "年龄" + i.ToString()); // } // util.SetRange(1, 1, 10, 4); // util.SetAliment(Excel.XlHAlign.xlHAlignCenter, Excel.XlVAlign.xlVAlignCenter); // //util.SetBorders(Excel.XlLineStyle.xlSlantDashDot); // util.SetLeftBorder(Excel.XlLineStyle.xlContinuous); // string exportPath = string.Format(@"{0}{1}", dir, "1.xlsx"); // util.SaveAs(exportPath); //} #endregion Console.Read(); }
/// <summary> /// 导入 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="stream">文件流</param> /// <returns></returns> public async Task <ImportResult <T> > ImportAsync <T>(Stream stream) where T : class, new() { var import = await ExcelImporter.Import <T>(stream); return(import); }
private void btn_star_ClickAsync(object sender, EventArgs e) { //若有缺失用户直接指定 曾丽蓉 string filepath = this.tb_filePath.Text; IExcelImporter Importer = new ExcelImporter(); var result = Importer.Import <ExcelModel>(filepath); if (result.Result.Data == null) { MessageBox.Show("读取excel失败!"); return; } List <ExcelModel> list = result.Result.Data.ToList(); //TODO: 将excel 拆成5张表 TASM_SUPPORT_Da daSupport = new TASM_SUPPORT_Da(); daSupport.Db.BeginTran(); //事务开 try { int i = 0; foreach (var item in list) { i++; logger.Info("===============导入开始==============" + i); Log("===============导入开始==============" + i); int sid = 0; //工单id TASM_SUPPORT supportModel = new TASM_SUPPORT(); Log("No:" + i + "创建工单-开始"); if (!CreateSupport(daSupport, item, ref sid, ref supportModel)) { daSupport.Db.RollbackTran(); logger.Info("===============导入失败====创建工单失败==========" + item.Content); Log("No:" + i + "创建工单-失败"); continue; } Log("No:" + i + "创建工单-结束"); //判断是否有现场处理节点, if (item.IsDisposerPoint.Trim() == "否" || string.IsNullOrWhiteSpace(item.IsDisposerPoint)) { //没有的话,继续下一条 Log("===============导入结束=========没有Disposer节点=====" + i); continue; } Log("No:" + i + "现场处理-开始"); if (!CreateDisposer(supportModel, item, sid)) { daSupport.Db.RollbackTran(); logger.Info("===============导入失败====创建现场处理失败==========" + item.Content); Log("No:" + i + "现场处理-失败"); continue; } Log("No:" + i + "现场处理-结束"); if (item.IsPmcPoint.Trim() == "否" || string.IsNullOrWhiteSpace(item.IsPmcPoint)) { //没有的话,继续下一条 Log("===============导入结束=========没有Pmc节点=====" + i); continue; } Log("No:" + i + "PMC处理-开始"); if (!CreatePmcOrder(supportModel, item, sid)) { daSupport.Db.RollbackTran(); logger.Info("===============导入失败====PMC处理失败==========" + item.Content); Log("No:" + i + "PMC处理失败-失败"); continue; } Log("No:" + i + "PMC处理-结束"); if (item.IsSitePoint == "否" || string.IsNullOrWhiteSpace(item.IsSitePoint)) { //没有的话,继续下一条 Log("===============导入结束=========没有site节点=====" + i); continue; } Log("No:" + i + "现场处理-开始"); if (!CreateSiteCheck(supportModel, item, sid)) { daSupport.Db.RollbackTran(); logger.Info("===============导入失败====现场处理失败==========" + item.Content); Log("No:" + i + "现场处理失败-失败"); continue; } Log("No:" + i + "现场处理-结束"); if (item.IsPrincipalPoint == "否" || string.IsNullOrWhiteSpace(item.IsPrincipalPoint)) { Log("===============导入结束=========没有principal节点=====" + i); continue; } if (!CreatePrincipal(supportModel, item, sid)) { daSupport.Db.RollbackTran(); logger.Info("===============导入失败====审核失败==========" + item.Content); Log("No:" + i + "审核处理失败-失败"); continue; } Log("===============导入结束==============" + i); logger.Info("===============导入结束==============" + i); } } catch (Exception ex) { daSupport.Db.RollbackTran(); logger.Info("程序异常,外层捕捉:" + ex); } }
private static DataSet LoadDataSet(string folder) { var importer = new ExcelImporter(folder); return(importer.Import("Clean CaDET")); }
private void btn_star_Click(object sender, EventArgs e) { logger.Debug("Debug"); logger.Info("Info"); logger.Error("Error"); logger.Warn("Warn"); string filepath = this.tb_filePath.Text; IExcelImporter Importer = new ExcelImporter(); var result = Importer.Import <ExcelModel>(filepath); if (result.Result.Data == null) { MessageBox.Show("读取excel失败!" + result.Result.Exception); return; } List <ExcelModel> list = result.Result.Data.ToList(); int i = 0; foreach (var item in list) { TASM_SUPPORT_Da daSupport = new TASM_SUPPORT_Da(); daSupport.Db.BeginTran(); //事务开 i++; logger.Info("===============导入开始==============" + i); Log("===============导入开始==============" + i); int sid = 0; //工单id TASM_SUPPORT supportModel = new TASM_SUPPORT(); Log("No:" + i + "创建工单-开始"); if (!CreateSupport(daSupport, item, ref sid, ref supportModel)) { logger.Info("===============导入失败====创建工单失败==========" + item.Content); Log("No:" + i + "创建工单-失败"); Log("===============导入失败====创建工单失败==========" + item.Content); daSupport.Db.RollbackTran(); continue; } Log("No:" + i + "创建工单-结束 sid:" + sid); //判断是否有技术处理节点, if (item.IsDisposerPoint.Trim() == "否" || string.IsNullOrWhiteSpace(item.IsDisposerPoint)) { //没有的话,继续下一条 Log("===============导入结束=========没有Disposer节点=====" + i); logger.Info("===============导入结束=========没有Disposer节点=====" + i); daSupport.Db.CommitTran(); continue; } Log("No:" + i + "技术处理-开始"); if (!CreateDisposer(supportModel, item, sid)) { logger.Info("===============导入失败====创建技术处理失败==========" + item.Content); Log("No:" + i + "技术处理-失败"); Log("===============导入失败====创建技术处理失败==========" + item.Content); daSupport.Db.RollbackTran(); continue; } Log("No:" + i + "技术处理-结束" + sid); //既没有PMC节点 也没有 site节点,则表示 没有PMC处理,也没有 现场处理,则该订单直接判断,审核环节也不要了, 直接下一条 if ((item.IsPmcPoint.Trim() == "否" || string.IsNullOrWhiteSpace(item.IsPmcPoint)) && (item.IsSitePoint == "否" || string.IsNullOrWhiteSpace(item.IsSitePoint))) { //没有的话,继续下一条 Log("===============导入结束=========没有Pmc节点=====" + i); logger.Info("===============导入结束=========没有Pmc节点=====" + i); daSupport.Db.CommitTran(); continue; } // 如果是有PMC 节点, 则插入PMC节点, 该情况可能发生,没有PMC节点,但是有site节点。所以 这里判断有PMC则插入,没有则还是要下去判断site节点。 if (item.IsPmcPoint.Trim() == "是") { Log("No:" + i + "PMC处理-开始"); if (!CreatePmcOrder(supportModel, item, sid)) { logger.Info("===============导入失败====PMC处理失败==========" + item.Content); Log("No:" + i + "PMC处理失败-失败"); Log("===============导入失败====PMC处理失败==========" + item.Content); daSupport.Db.RollbackTran(); continue; } Log("No:" + i + "PMC处理-结束"); } if (item.IsSitePoint == "否" || string.IsNullOrWhiteSpace(item.IsSitePoint)) { //没有的话,继续下一条 logger.Info("===============导入结束=========没有site节点=====" + i); Log("===============导入结束=========没有site节点=====" + i); daSupport.Db.CommitTran(); continue; } Log("No:" + i + "现场处理-开始"); if (!CreateSiteCheck(supportModel, item, sid)) { logger.Info("===============导入失败====现场处理失败==========" + item.Content); Log("No:" + i + "现场处理失败-失败"); Log("===============导入失败====现场处理失败==========" + item.Content); daSupport.Db.RollbackTran(); continue; } Log("No:" + i + "现场处理-结束"); if (item.IsPrincipalPoint == "否" || string.IsNullOrWhiteSpace(item.IsPrincipalPoint)) { logger.Info("===============导入结束=========没有principal节点=====" + i); Log("===============导入结束=========没有principal节点=====" + i); daSupport.Db.CommitTran(); continue; } if (!CreatePrincipal(supportModel, item, sid)) { logger.Info("===============导入失败====审核失败==========" + item.Content); Log("No:" + i + "审核处理失败-失败"); Log("===============导入失败====审核失败==========" + item.Content); daSupport.Db.RollbackTran(); continue; } daSupport.Db.CommitTran(); Log("===============导入结束==============" + i); logger.Info("===============导入结束==============" + i); } }