Ejemplo n.º 1
0
 // sau khi add xong thuc hien cham diem, cham den dau in diem den day!
 private void ExportButton_Click(object sender, EventArgs e)
 {
     try
     {
         double maxPoint = 0;
         foreach (var candidate in ListResults.ElementAt(0).ListCandidates)
         {
             maxPoint += candidate.Point;
         }
         ExcelUtils.ExportResultsExcel(ListResults, ListSubmissions, maxPoint,
                                       ListResults.ElementAt(0).ListCandidates.Count);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error");
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 导出元数据页
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="sheetName"></param>
        private void ExportMetadataSheet(IWorkbook workbook, string sheetName)
        {
            if (sheetMetadata == null)
            {
                return;
            }
            ISheet sheet = workbook.CreateSheet(sheetName);
            ICell  cell  = sheet.CreateRow(0).CreateCell(0);

            cell.SetCellType(CellType.String);

            string xmlString = ExcelUtils.XmlSerialize <SheetMetadata>(sheetMetadata);

            //wyf
            //xmlString = PublicUtils.Base64(xmlString, true);
            cell.SetCellValue(xmlString);
        }
Ejemplo n.º 3
0
        public void WriteAllLines(Dictionary <string, string> dic, string path)
        {
            //直接写入excel
            var listTable = new ListTable()
            {
                Rows = dic.Select(p => new List <object>()
                {
                    p.Key, p.Value
                }).ToList(),
                Columns = new List <string>()
                {
                    "key", "value"
                }
            };

            ExcelUtils.ExportToExcel(listTable.ToDataTable(), Path.ChangeExtension(path, ".xlsx"));
        }
Ejemplo n.º 4
0
        public void Init(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return;
            }

            DataCount = dt.Rows.Count;
            ExcelUtils.UnLockSheet(this);

            LoadData(dt);

            SetFormula();

            ResetFormat();

            ExcelUtils.LockSheet(this);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 多个DataTable保存在同一文件
        /// </summary>
        public void ToOneExcel()
        {
            var dts = CheckPath(getSelectExtension).AsParallel().SelectMany(file =>
            {
                Console.WriteLine(" is now : " + file);
                return(import(file).Where(p => p != null).Select(p =>
                {
                    p.TableName = Path.GetFileNameWithoutExtension(file);
                    return p;
                }));
            }).ToList();

            if (dts.Count == 0)
            {
                return;
            }
            ExcelUtils.ExportToExcel(dts, InputPath);
        }
Ejemplo n.º 6
0
 public void ClearData()
 {
     try
     {
         ExcelUtils.UnLockSheet(this);
         if (DataCount > 0)
         {
             Excel.Range rg;
             rg = this.Range[string.Format(DATA_ROW, TITLE_ROW_COUNT + 1, TITLE_ROW_COUNT + DataCount)];
             rg.Clear();
         }
         ExcelUtils.LockSheet(this);
     }
     catch (Exception ex)
     {
         LogHelper.WriteError("", ex);
     }
 }
Ejemplo n.º 7
0
        public ActionResult LastReadable(int id)
        {
            var           workbook = new XLWorkbook();
            JourEvenement jour;

            using (var ctx = new FestivArtsContext())
            {
                jour = ctx.JourEvenements.First(s => s.Id == id);
                Planning p = ctx.Plannings.Include("Affectations.Benevole").OrderByDescending(s => s.Date).FirstOrDefault();


                ExcelUtils.FillPlanning(workbook, ctx, jour, p, true);
            }
            var stream = new MemoryStream();

            workbook.SaveAs(stream);
            stream.Position = 0;
            return(File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Planning" + jour.Nom + ".xlsx"));
        }
Ejemplo n.º 8
0
        public void Load(string filePath)
        {
            m_columnNames = new List <string>();

            var table = ExcelUtils.ReadCsv(filePath);

            for (int i = 0; i < table.Columns.Count; ++i)
            {
                m_columnNames.Add(table.Columns[i].ColumnName);
            }

            for (int i = 0; i < table.Rows.Count; ++i)
            {
                var  record        = new CollateralCsvRecord();
                bool isValidRecord = true;
                for (int j = 0; j < table.Columns.Count; ++j)
                {
                    var columnName = m_columnNames[j];
                    var cellValue  = table.Rows[i].ItemArray[j].ToString();
                    if (columnName.Equals("AssetId", StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (string.IsNullOrEmpty(cellValue))
                        {
                            isValidRecord = false;
                            break;
                        }

                        record.AssetId = int.Parse(cellValue);
                    }
                    else
                    {
                        record.Items[columnName] = cellValue;
                    }
                }

                if (isValidRecord)
                {
                    this.Add(record);
                }
            }

            FilePath = filePath;
        }
Ejemplo n.º 9
0
 public void OnEnable()
 {
     assetPath = AssetDatabase.GetAssetPath(target);
     if (assetPath.IsExcel())
     {
         var book = ExcelUtils.Open(assetPath);
         var tmp  = new BookStruct();
         tmp.Name = assetPath;
         tmp.Book = book;
         foreach (var sheet in book.AllSheets())
         {
             var ss = new SheetStruct();
             ss.Name  = sheet.SheetName;
             ss.Sheet = sheet;
             tmp.Sheets.Add(ss);
         }
         mTarget = tmp;
     }
 }
Ejemplo n.º 10
0
        /// <summary> 匯出報表 - EXCEL </summary>
        /// <param name="data"></param>
        /// <param name="exportFileName"></param>
        /// <returns></returns>
        private string ExportData(DataSet data, string exportFileName)
        {
            var fileName = string.Empty;

            switch (reportSetting.ExportType)
            {
            default:
            case ExportType.CSV:
                fileName = string.Format("{0}_{1}.csv", exportFileName, DateTime.Now.ToString("yyyyMMddHHmmss"));
                CsvUtils.export(data, reportSetting.ExportPH, fileName);
                break;

            case ExportType.EXCEL:
                fileName = string.Format("{0}_{1}.xls", exportFileName, DateTime.Now.ToString("yyyyMMddHHmmss"));
                ExcelUtils.export(data, reportSetting.ExportPH, fileName);
                break;
            }
            return(fileName);
        }
        private StandardTableDataCM CreateStandardTableCMFromExcelFile(byte[] excelFile, string excelFileExtension)
        {
            var rowsDictionary = ExcelUtils.GetTabularData(excelFile, excelFileExtension, false);

            if (rowsDictionary != null)
            {
                var rows = ExcelUtils.CreateTableCellPayloadObjects(rowsDictionary);
                if (rows != null)
                {
                    return(new StandardTableDataCM
                    {
                        FirstRowHeaders = false,
                        Table = rows
                    });
                }
            }

            return(null);
        }
        private decimal GetVATRate(IExcelDataReader reader, SheetConfig config, decimal defaultVatRate)
        {
            if (!config.VatRates.Any())
            {
                return(defaultVatRate);
            }

            foreach (var rate in config.VatRates)
            {
                var index = ExcelUtils.ColumnToIndex(rate.Column);
                var value = Utils.GetValue(reader, index).TrimWhiteSpace();

                if (value.IgnoreCaseEquals(rate.Value))
                {
                    return(rate.Rate);
                }
            }

            return(defaultVatRate);
        }
        public async Task GetAllSortedMaxCurrRatiosTest()
        {
            try
            {
                DateTime        startTime       = DateTime.Now.AddHours(-1);
                DateTime        endTime         = startTime.AddMinutes(1);
                FaultSortEngine faultSortEngine = new FaultSortEngine();
                faultSortEngine.GetLinesInfoFromDb();
                List <Tuple <double, string, DateTime> > sortedMaxCurrRatios = await faultSortEngine.GetAllSortedMaxCurrRatios(faultSortEngine.WindowStartTime, faultSortEngine.WindowEndTime);

                List <double> sortedMaxCurrRatioVals = sortedMaxCurrRatios.Select(ratioTuple => ratioTuple.Item1).ToList();
                // dump the results to excel
                string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss");
                ExcelUtils.DumpCurrRatioResultsToExcel(sortedMaxCurrRatios, $"E:\\sortedCurrRatios{dateStr}.xlsx");
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }
        }
Ejemplo n.º 14
0
        private void RunImport(string path, Encoding encode)
        {
            var dt = ExcelUtils.ReadDataFile(path, encode);

            dtImport = dt;
            foreach (DataRow item in dt.Rows)
            {
                if (item.ItemArray.Length > 2 && Regex.IsMatch(item[1].ToString(), "^[0-9]{1,5}$"))
                {
                    item[1] = Utils.AutoAddZero(item[1].ToString());
                }
            }
            dtImport.TableName = path.Substring(path.LastIndexOf('\\') + 1);
            this.Dispatcher.Invoke(() =>
            {
                this.dgImportData.ItemsSource = dtImport.DefaultView;
                txtMsg.AppendText(string.Format("已读取文件{0},数据共{1}行.{2}", path, dt.Rows.Count, Environment.NewLine));
                this.loading.HideLoading();
            });
        }
Ejemplo n.º 15
0
        public HttpResponseMessage GetExcel(int moduleId, int tabId, string template, string fileName)
        {
            ModuleController        mc       = new ModuleController();
            IEnumerable <IDataItem> dataList = new List <IDataItem>();
            var module   = new OpenContentModuleInfo(moduleId, tabId);
            var manifest = module.Settings.Template.Manifest;

            if (!OpenContentUtils.HasAllUsersViewPermissions(PortalSettings, module.ViewModule))
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            bool useLucene = module.Settings.Template.Manifest.Index;

            if (useLucene)
            {
                var indexConfig = OpenContentUtils.GetIndexConfig(module.Settings.Template);

                QueryBuilder queryBuilder = new QueryBuilder(indexConfig);
                queryBuilder.Build(module.Settings.Query, PortalSettings.UserMode != PortalSettings.Mode.Edit, UserInfo.UserID, DnnLanguageUtils.GetCurrentCultureCode(), UserInfo.Social.Roles);

                IDataSource ds        = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource);
                var         dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID);

                var dsItems = ds.GetAll(dsContext, queryBuilder.Select);
                dataList = dsItems.Items;
            }

            var     mf    = new ModelFactoryMultiple(dataList, null, module.Settings.TemplateDir.PhysicalFullDirectory, manifest, null, null, module, PortalSettings);
            dynamic model = mf.GetModelAsDictionary(true);

            var    rssTemplate = new FileUri(module.Settings.TemplateDir, template + ".hbs");
            string source      = rssTemplate.FileExists ? FileUriUtils.ReadFileFromDisk(rssTemplate) : GenerateCsvTemplateFromModel(model, rssTemplate);

            HandlebarsEngine hbEngine = new HandlebarsEngine();
            string           res      = hbEngine.Execute(source, model);

            var fileBytes = ExcelUtils.OutputFile(res);

            return(ExcelUtils.CreateExcelResponseMessage(fileName, fileBytes));
        }
Ejemplo n.º 16
0
        public void CreateExcel()
        {
            string dllPath           = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string excelTemplatePath = dllPath.Replace("application\\", "Cofigure\\ShopDoc_Template-test.xlsx");
            string path = part.FullPath;

            path = System.IO.Path.GetDirectoryName(path) + "\\" + part.Name + ".xlsx";

            IWorkbook workbook = ExcelUtils.CreateExeclFile(excelTemplatePath);

            if (workbook == null)
            {
                return;
            }
            IFont font = workbook.CreateFont();

            font.FontName           = "微软雅黑";
            font.FontHeightInPoints = 8;
            ICellStyle style     = ExcelUtils.SetCellStyle(workbook, font);
            ICellStyle styleDate = ExcelUtils.SetCellStyle(workbook, font);

            styleDate.DataFormat = 21;
            ISheet   sheet = workbook.GetSheetAt(0);
            MoldInfo mold  = this.info.GetMoldInfo();

            if (this.info.IsWorkpiece())
            {
                SetMoldInfoToExcel(mold, sheet, style);
            }
            else
            {
                SetEleMoldInfoToExcel(mold, sheet, style);
            }
            SetUser(sheet, style);
            SetRowData(sheet, style, styleDate);
            FileStream fs = File.Create(path);

            workbook.Write(fs);
            fs.Close();
            workbook.Close();
        }
Ejemplo n.º 17
0
        public void ClearFilter()
        {
            try
            {
                if (!this.AutoFilter.FilterMode || DataCount == 0)
                {
                    return;
                }

                ExcelUtils.UnLockSheet(this);
                for (int i = 1; i < columns.Length + 1; i++)
                {
                    this.Range[string.Format(DATA_ROW, TITLE_ROW_COUNT + 1, TITLE_ROW_COUNT + DataCount)].AutoFilter(i, System.Type.Missing, Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd, System.Type.Missing, true);
                }
                ExcelUtils.LockSheet(this);
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("", ex);
            }
        }
Ejemplo n.º 18
0
 private bool ReadToDataTable(string FileName, out DataTable dt, out string errMsg)
 {
     dt     = null;
     errMsg = null;
     try
     {
         dt = CommonUtils.IsExcel(FileName) ?  ExcelUtils.ReadExcel(FileName) : CommonUtils.ReadCSV(FileName);
         FixTableData(dt);
         dt.TableName = FileName;
         return(true);
     }
     catch (NPOI.POIFS.FileSystem.NotOLE2FileException)
     {
         errMsg = "文件格式不正确,请尝试用Excel另存为后打开";
     }
     catch (Exception ex)
     {
         errMsg = ex.Message;
     }
     return(false);
 }
Ejemplo n.º 19
0
        public KvExcelTo(object obj) : base()
        {
            KvExcelTo(isCustomAction: (fullpath, list) =>
            {
                Dictionary <string, JsonData> dictionary = new Dictionary <string, JsonData>();
                foreach (List <object> objects in list)
                {
                    object id          = objects[1];
                    string key         = objects[2].ToString();
                    object value       = objects[3];
                    string value_zh_cn = objects[4].ToString();

                    dictionary[id.ToString()] = value_zh_cn;
                }

                JsonData jsonData = JsonHelper.ToObject(File.ReadAllText(fullpath).Trim().Trim('\0'));
                JsonHelper.RevertDictionaryToJson(jsonData, dictionary);
                return(ExcelUtils.ExportToJson(jsonData));
            }, isArray: (bool)obj
                      );
        }
Ejemplo n.º 20
0
        private void button6_Click(object sender, EventArgs e)
        {
            //通过excel数据生成insertSql语句
            (new FrmExcel()).ShowDialog();
            return;

            string filePath = "";

            #region choose import file
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "(Microsoft Excel 2013;Microsoft Excel 2007)|*.xlsx;*.xls";
            DialogResult dialogResult = dialog.ShowDialog();
            if (DialogResult.Cancel == dialogResult)
            {
                return;
            }
            else if (DialogResult.OK == dialogResult)
            {
                filePath = dialog.FileName;
            }
            #endregion

            string result     = "";
            var    sheetNames = ExcelUtils.GetXlsSheetnames(filePath, out result);
            //DataSet ds = FileUtils.GetExcelDataSet(filePath);
            //string tableName = ds.Tables[0].Rows[2 - 1][1 - 1].ToString(), insertColumnList = "";
            //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            //{
            //    insertColumnList += string.Format(ds.Tables[0].Rows[3 - 1][i].ToString() + ",");
            //}
            //insertColumnList = deleteLastDouhao(insertColumnList);  //去除最后的,号
            ////insert inot tb() values
            //StringBuilder sbSql = new StringBuilder();
            //sbSql.AppendFormat(("insert into "));
            //sbSql.AppendFormat(tableName);
            //sbSql.AppendFormat(@"(");
            //sbSql.AppendFormat(insertColumnList);
            //sbSql.AppendFormat(@") values (");
            //sbSql.AppendFormat(@");");
        }
        /// <summary>
        /// 开始检查译文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void click_BeginCheckFile(object sender, RoutedEventArgs e)
        {
            //1 首先要有译文
            string filePath = tbFilePath.Text;

            if (File.Exists(filePath))
            {
                //还没设置译文列位置
                if (Argument.TargetColumn > 0 == false)
                {
                    User_SetUp(sender, e);
                }
                //格式转换xls-->xlsx
                if (filePath.EndsWith(".xls"))
                {
                    filePath = ConvertWorkbook(filePath, Argument.OutPutDiretory);
                }
                try
                {
                    //2 判断是否规范
                    if (ExcelUtils.IsTranslationFile(filePath))
                    {
                        //3 将参数交由后台线程去做主要的事情
                        backgroundWorker.RunWorkerAsync(new InputContainer(filePath));
                        btnHandle.IsEnabled   = false;
                        btnOpenFile.IsEnabled = false;
                    }
                }
                catch (Exception)
                {
                    OpenWindowsUtils.OpenMyMessageBox(false, "文件已被其它程序占用,请关闭占用该文件的程序",
                                                      "The file has been occupied by other programs.",
                                                      this);
                }
            }
            else
            {
                OpenWindowsUtils.OpenMyMessageBox(false, "请您选择待检测的译文文件", "Please select the translation file", this);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// excel 转换为jtcy 对象
        /// </summary>
        /// <param name="path">Excel路径</param>
        /// <returns></returns>
        public static ObservableCollection <JTCY> GetExcelToHZS(string path)
        {
            ObservableCollection <JTCY> list = ExcelUtils.GetExcelToObjectToObservableCollection <JTCY>(path, XMLPath);
            ObservableCollection <JTCY> hzs  = GetJTCYSToHz(list);

            //户主放在第一位
            for (int b = 0; b < hzs.Count; b++)
            {
                JTCY hz = hzs[b];
                if (Utils.IsStrNull(hz.GMSFHM))
                {
                    hzs.RemoveAt(b);
                    b--;
                    continue;
                }
                IList <JTCY> jTCies = hz.JTCies;
                for (int a = 1; a < jTCies.Count; a++)
                {
                    JTCY jTCY = jTCies[a];
                    if (jTCY.YHZGX == "户主")
                    {
                        jTCies.RemoveAt(a);
                        jTCies.Insert(0, jTCY);
                        break;
                    }
                }
                for (int a = 2; a < jTCies.Count; a++)
                {
                    JTCY jTCY = jTCies[a];
                    if (jTCY.YHZGX == "妻")
                    {
                        jTCies.RemoveAt(a);
                        jTCies.Insert(1, jTCY);
                        break;
                    }
                }
            }

            return(hzs);
        }
Ejemplo n.º 23
0
        public void Load(string filePath)
        {
            Clear();

            if (!File.Exists(filePath))
            {
                return;
            }

            var dt = ExcelUtils.ReadCsv(filePath);

            for (int i = 0; i < dt.Rows.Count; ++i)
            {
                var row = dt.Rows[i];
                if (row.ItemArray.Length < 3)
                {
                    continue;
                }

                int      assetId;
                DateTime reductionDate;
                double   reductionAmount;
                if (int.TryParse(row.ItemArray[0].ToString(), out assetId) &&
                    DateTime.TryParse(row.ItemArray[1].ToString(), out reductionDate) &&
                    double.TryParse(row.ItemArray[2].ToString(), out reductionAmount) &&
                    MathUtils.MoneyNE(reductionAmount, 0))
                {
                    var record = new AmortizationScheduleRecord()
                    {
                        AssetId         = assetId,
                        ReductionDate   = reductionDate,
                        ReductionAmount = reductionAmount
                    };

                    Add(record);
                }
            }

            m_filePath = filePath;
        }
Ejemplo n.º 24
0
        private void Button_Upload_Click(object sender, RoutedEventArgs e)
        {
            if (!ViewModel.Files.Any(f => f.IsSelected))
            {
                MessageBox.Show("Не выбран файл", "Внимание!");
                return;
            }
            foreach (var file in ViewModel.Files.Where(f => f.IsSelected))
            {
                var hasError = false;
                foreach (var person in ExcelUtils.LoadInputForm(file.Path))
                {
                    var sql = $@"
EXECUTE pr_AddPerson
   '{person.PassportSerial}'
  ,'{person.LastName}'
  ,'{person.FirstName}'
  ,'{person.Patronymic}'
  ,'{person.BirthDate}'
  ,'{person.BirthPlace}'
  ,'{person.PassportIssue}'
  ,'{person.PassportIssueDate}'
  ,'{person.PassportDivisionCode}'
  ,'{person.Address}'
  ,'{person.PhoneHome}'
  ,'{person.PhoneMobile}'
  ,{person.RecruitmentOfficeID}
  ,'{person.Codeword}'
  ,'{person.Comment}'
";
                    using (var sqlComm = new SqlCommandExecutor(sql))
                        if (!sqlComm.TryExecuteNonQuery(out _))
                        {
                            hasError = true;
                        }
                }
                file.IsImported = !hasError;
                file.HasError   = hasError;
            }
        }
Ejemplo n.º 25
0
        public void Save(string filePath = null)
        {
            DataTable dtAmort = new DataTable();

            dtAmort.Columns.Add("AssetId");
            dtAmort.Columns.Add("ReductionDate");
            dtAmort.Columns.Add("ReductionAmount");

            var list = this.OrderBy(x => x.AssetId).ThenBy(x => x.ReductionDate);

            foreach (var record in list)
            {
                dtAmort.Rows.Add(record.AssetId, record.ReductionDate.ToString("yyyy/MM/dd"), record.ReductionAmount.ToString("n2"));
            }

            if (string.IsNullOrEmpty(filePath))
            {
                filePath = m_filePath;
            }

            ExcelUtils.WriteCsv(dtAmort, filePath);
        }
Ejemplo n.º 26
0
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("请使用下载的模板进行导入!!!!\n是否下载模板(选否则直接选择文件导入)", "提示", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                string localFilePath = "";
                //string localFilePath, fileNameExt, newFileName, FilePath;
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                //设置文件类型
                sfd.Filter = "Excel表格(*.xls)|*.xls";

                //设置默认文件类型显示顺序
                sfd.FilterIndex = 1;

                //保存对话框是否记忆上次打开的目录
                sfd.RestoreDirectory = true;

                //点了保存按钮进入
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    localFilePath = sfd.FileName.ToString(); //获得文件路径
                    ExcelUtils.downModel(localFilePath);
                }
            }
            if (result == MessageBoxResult.No)
            {
                System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
                fileDialog.Multiselect = true;
                fileDialog.Title       = "请选择文件";
                fileDialog.Filter      = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
                if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string file = fileDialog.FileName;//返回文件的完整路径
                    ExcelUtils.import(file, departmentId);
                    refreashMember();
                }
            }
        }
Ejemplo n.º 27
0
        private VariablesInfo LoadFromFile(string filename)
        {
            var       filepath = Path.Combine(m_dsFolder, filename);
            DataTable dt       = ExcelUtils.ReadCsv(filepath);
            DateTime  d;
            List <VariablesCsvRecord> values = new List <VariablesCsvRecord>();
            var columns = dt.Columns.Cast <DataColumn>().Select(o => o.ColumnName.Trim().ToLower())
                          .Select(o => DateTime.TryParse(o, out d) ? o : "")
                          .Where(o => !String.IsNullOrEmpty(o))
                          .ToList();

            foreach (DataRow row in dt.Rows)
            {
                var name = row.Field <string>("Name");
                var des  = row.Field <string>("Description");
                if (String.IsNullOrEmpty(name))
                {
                    continue;
                }
                VariablesCsvRecord item = new VariablesCsvRecord()
                {
                    Name        = name,
                    Description = des
                };
                values.Add(item);
                foreach (var col in columns)
                {
                    var    date  = Convert.ToDateTime(col);
                    string value = row[col] == DBNull.Value ? "" : row[col].ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        item.Items.Add(date, value);
                    }
                }
            }
            return(new VariablesInfo {
                Variables = values, Dates = columns.Select(o => Convert.ToDateTime(o)).ToList()
            });
        }
Ejemplo n.º 28
0
        private static List <ReviewFields> ParceInputFile(MemoryStream input)
        {
            List <ReviewFields> rfs           = new List <ReviewFields>();
            SpreadsheetDocument ssd           = SpreadsheetDocument.Open(input, true);
            WorkbookPart        workbookPart  = ssd.WorkbookPart;
            WorksheetPart       worksheetPart = workbookPart.WorksheetParts.FirstOrDefault();
            Sheets sheets = workbookPart.Workbook.Sheets;
            Sheet  sheet  = sheets.GetFirstChild <Sheet>();

            SheetData             sheetData        = worksheetPart.Worksheet.Descendants <SheetData>().FirstOrDefault();
            SharedStringTablePart sharedStringPart = workbookPart.SharedStringTablePart;

            foreach (var row in sheetData.Elements <Row>())
            {
                if (row.RowIndex == 1)
                {
                    continue;
                }
                ReviewFields rf = new ReviewFields();
                rf.Discipline   = ExcelUtils.GetCellText(sharedStringPart, row, "A");
                rf.Theme        = ExcelUtils.GetCellText(sharedStringPart, row, "B");
                rf.StudentName  = ExcelUtils.GetCellText(sharedStringPart, row, "C");
                rf.StudentGroup = ExcelUtils.GetCellText(sharedStringPart, row, "D");
                rf.ChiefName    = ExcelUtils.GetCellText(sharedStringPart, row, "E");
                uint number;
                if (UInt32.TryParse(ExcelUtils.GetCellText(sharedStringPart, row, "F"), out number))
                {
                    rf.Evaluation = number;
                }
                else
                {
                    rf.Evaluation = 0;
                }
                rf.EvaluatonsSet = GetRandomEvaluationsSet(rf.Evaluation);
                rfs.Add(rf);
            }
            ssd.Close();
            return(rfs);
        }
Ejemplo n.º 29
0
        public ICellStyle AppendStyleTaskStatus(ICellStyle style, Cell cell)
        {
            if (cell.IsEmpty)
            {
                return(AppendStyleDefaultBorder(style));
            }
            var cellValue = cell.GetCellValue();

            if (cellValue == "完成" || cellValue == "错误")
            {
                return(ExcelUtils.GetFontColorStyle(m_workbook.GetIWorkbook(), ExcelFontColor.Green));
            }
            else if (cellValue == "进行中" || cellValue == "等待")
            {
                return(ExcelUtils.GetFontColorStyle(m_workbook.GetIWorkbook(), ExcelFontColor.Blue));
            }
            else if (cellValue == "逾期")
            {
                return(ExcelUtils.GetFontColorStyle(m_workbook.GetIWorkbook(), ExcelFontColor.Red));
            }
            return(style);
        }
Ejemplo n.º 30
0
        public IHttpActionResult Gather()
        {
            try
            {
                var request = Context.AuthenticatedRequest;
                var siteId  = request.GetQueryInt("siteId");
                var ruleId  = request.GetQueryInt("ruleId");

                if (!request.IsAdminLoggin ||
                    !request.AdminPermissions.HasSitePermissions(siteId, Utils.PluginId))
                {
                    return(Unauthorized());
                }

                var channelId  = request.GetPostInt("channelId");
                var guid       = request.GetPostString("guid");
                var gatherType = request.GetPostString("gatherType");
                var fileName   = request.GetPostString("fileName");
                var urls       = TranslateUtils.StringCollectionToStringList(request.GetPostString("urls"), '\n');
                if (gatherType == "excel")
                {
                    var filePath = Context.UtilsApi.GetTemporaryFilesPath(fileName);
                    urls = ExcelUtils.GetContentUrls(filePath);
                }

                var adminInfo = Context.AdminApi.GetAdminInfoByUserId(request.AdminId);

                Main.GatherRuleRepository.GatherContents(adminInfo, siteId, ruleId, channelId, guid, urls);

                return(Ok(new
                {
                    Value = true
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }