private void ExportXlsx(object sender, RoutedEventArgs e) { //export the combined PDF SaveFileDialog dialog = new SaveFileDialog() { DefaultExt = "xlsx", Filter = String.Format("Workbooks (*.{0})|*.{0}|All files (*.*)|*.*", "xlsx"), FilterIndex = 1 }; if (dialog.ShowDialog() == true) { //export the data from the two RadGridVies instances in separate documents Workbook playersDoc = this.playersGrid.ExportToWorkbook(); Workbook clubsDoc = this.clubsGrid.ExportToWorkbook(); //merge the second document into the first one Worksheet clonedSheet = playersDoc.Worksheets.Add(); clonedSheet.CopyFrom(clubsDoc.Sheets[0] as Worksheet); using (Stream stream = dialog.OpenFile()) { new XlsxFormatProvider().Export(playersDoc, stream); } } }
private void button1_Click(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.FileName = "result.csv"; dialog.Filter = "CSVファイル(*.csv)|*.csv|全てのファイル(*.*)|*.*"; dialog.OverwritePrompt = true; dialog.CheckPathExists = true; bool? res = dialog.ShowDialog(); if (res.HasValue && res.Value) { try { if (mainWin.fileWriter != null) mainWin.fileWriter.Flush(); System.IO.Stream fstream = dialog.OpenFile(); System.IO.Stream fstreamAppend = new System.IO.FileStream(dialog.FileName+"-log.csv", System.IO.FileMode.OpenOrCreate); if (fstream != null && fstreamAppend != null) { textBox1.Text = dialog.FileName; mainWin.fileWriter = new System.IO.StreamWriter(fstream); mainWin.logWriter = new System.IO.StreamWriter(fstreamAppend); } } catch (Exception exp) { MessageBox.Show(exp.ToString()); } } }
// What to do when the user wants to export a TeX file private void exportHandler(object sender, EventArgs e) { Stream stream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "SVG files|(*.svg"; saveFileDialog.RestoreDirectory = true; if(saveFileDialog.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog.OpenFile()) != null) { // Insert code here that generates the string of LaTeX // commands to draw the shapes using(StreamWriter writer = new StreamWriter(stream)) { writer.Write("<?xml version='1.0' standalone='no'?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg xmlns='http://www.w3.org/2000/svg' version='1.1'> "); Visual visual = new VisualSVG(writer); //Draw all shapes foreach (Shape shape in shapes) { shape.visual = visual; shape.Draw(); } writer.Write("</svg>"); } } } }
public void Export(object parameter) { RadGridView grid = parameter as RadGridView; if (grid != null) { grid.ElementExporting -= this.ElementExporting; grid.ElementExporting += this.ElementExporting; grid.ElementExported -= this.ElementExported; grid.ElementExported += this.ElementExported; string extension = "xls"; ExportFormat format = ExportFormat.Html; SaveFileDialog dialog = new SaveFileDialog(); dialog.DefaultExt = extension; dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"); dialog.FilterIndex = 1; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { GridViewExportOptions options = new GridViewExportOptions(); options.Format = format; options.ShowColumnHeaders = true; options.Encoding = System.Text.Encoding.UTF8; grid.Export(stream, options); } } } }
private void ExportPdf(object sender, RoutedEventArgs e) { //export the combined PDF SaveFileDialog dialog = new SaveFileDialog() { DefaultExt = "pdf", Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", "pdf", "Pdf"), FilterIndex = 1 }; if (dialog.ShowDialog() == true) { //export the data from the two RadGridVies instances in separate documents RadFixedDocument playersDoc = this.playersGrid.ExportToRadFixedDocument(); RadFixedDocument clubsDoc = this.clubsGrid.ExportToRadFixedDocument(); //merge the second document into the first one playersDoc.Merge(clubsDoc); using (Stream stream = dialog.OpenFile()) { new PdfFormatProvider().Export(playersDoc, stream); } } }
// What to do when the user wants to export a SVG file private void exportHandler(object sender, EventArgs e) { Stream stream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "SVG files|*.svg"; saveFileDialog.RestoreDirectory = true; if(saveFileDialog.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog.OpenFile()) != null) { // Insert code here that generates the string of SVG // commands to draw the shapes String SVGtext = "<?xml version=\"1.0\" standalone=\"no\"?>" + "\r\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"" + "\r\n\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" + "\r\n<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"; foreach (Shape shape in shapes) { SVGtext = SVGtext + shape.Conversion("SVG"); } SVGtext = SVGtext + "\r\n</svg>"; using (StreamWriter writer = new StreamWriter(stream)) { // Write strings to the file here using: writer.WriteLine(SVGtext); } } } }
// What to do when the user wants to export a SVG file private void exportHandler(object sender, EventArgs e) { Stream stream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "SVG files|(*.svg)"; saveFileDialog.RestoreDirectory = true; if(saveFileDialog.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog.OpenFile()) != null) { //import header from a file. string[] header = { @"<?xml version =""1.0"" standalone=""no""?>", @"<!DOCTYPE svg PUBLIC ""-//W3C//DTD SVG 1.1//EN"" ""http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"">", @"<svg xmlns=""http://www.w3.org/2000/svg"" version=""1.1"">" }; //import the SVG shapes. using (StreamWriter writer = new StreamWriter(stream)) { foreach (string headerLine in header) { writer.WriteLine(headerLine); } foreach(Shape shape in shapes) { shape.drawTarget = new DrawSVG(); shape.Draw(); writer.WriteLine(shape.useShape); } writer.WriteLine("</svg>"); } } } }
public static void ExportDataGrid(DataGrid dGrid, String author, String companyName, String mergeCells, int boldHeaderRows, string fileName) { if (Application.Current.HasElevatedPermissions) { var filePath ="C:" + Path.DirectorySeparatorChar +"Nithesh"+Path.DirectorySeparatorChar +fileName + ".XML"; File.Create(filePath); Stream outputStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite); ExportToExcel(dGrid, author, companyName, mergeCells, boldHeaderRows, "XML", outputStream); } else { SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = FILE_FILTER, FilterIndex = 2, DefaultFileName = fileName }; if (objSFD.ShowDialog() == true) { string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper(); Stream outputStream = objSFD.OpenFile(); ExportToExcel(dGrid, author, companyName, mergeCells, boldHeaderRows, strFormat, outputStream); } } }
private async void CreateNewEndpoint_OnClick(object sender, RoutedEventArgs e) { this.CreateNewEndpoint.IsEnabled = false; this.CreateNewEndpoint.Cursor = Cursors.AppStarting; try { var cts = new CancellationTokenSource(); var endpointTask = this.OwnEndpointServices.CreateAsync(cts.Token); var dialog = new SaveFileDialog(); bool? result = dialog.ShowDialog(this); if (result.HasValue && result.Value) { Uri addressBookEntry = await this.OwnEndpointServices.PublishAddressBookEntryAsync(await endpointTask, cts.Token); await this.SetEndpointAsync(await endpointTask, addressBookEntry, cts.Token); using (var stream = dialog.OpenFile()) { var writer = new BinaryWriter(stream, Encoding.UTF8); writer.SerializeDataContract(addressBookEntry); writer.Flush(); await this.Channel.Endpoint.SaveAsync(stream, cts.Token); } } else { cts.Cancel(); } } finally { this.CreateNewEndpoint.Cursor = Cursors.Arrow; this.CreateNewEndpoint.IsEnabled = true; } }
protected void Save_Click(Object sender, EventArgs e) { SaveFileDialog s = new SaveFileDialog(); if(s.ShowDialog() == DialogResult.OK) { StreamWriter writer = new StreamWriter(s.OpenFile()); writer.Write(text.Text); writer.Close(); } }
// What to do when the user wants to export a TeX file private void exportHandler(object sender, EventArgs e) { Stream stream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Scalable Vector Graphics (*.svg)|*.svg|TeX files (*.tex)|*.tex"; saveFileDialog.RestoreDirectory = true; if(saveFileDialog.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog.OpenFile()) != null) { string name = saveFileDialog.FileName; string ext = Path.GetExtension(saveFileDialog.FileName).ToLower(); switch(ext){ case ".tex": LatexGenerator lg = new LatexGenerator(); using (StreamWriter writer = new StreamWriter(stream)) { lg.FileWriter = writer; writer.WriteLine("\\documentclass{article}"); writer.WriteLine("\\usepackage{tikz}"); writer.WriteLine("\\begin{document}"); writer.WriteLine("\\begin{tikzpicture}"); writer.WriteLine("\\begin{scope}[yscale= -3, xscale= 3]"); foreach(Shape s in this.shapes) { s.OutputApi = lg; s.Draw(); } writer.WriteLine("\\end{scope}"); writer.WriteLine("\\end{tikzpicture}"); writer.WriteLine("\\end{document}"); } break; default: //save as svg by default SvgGenerator sg = new SvgGenerator(); using (StreamWriter writer = new StreamWriter(stream)) { sg.FileWriter = writer; writer.WriteLine("<?xml version=\"1.0\" standalone=\"no\"?>"); writer.WriteLine("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">"); writer.WriteLine("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"); foreach (Shape s in this.shapes) { s.OutputApi = sg; s.Draw(); } writer.WriteLine("</svg>"); } break; } } } }
public override bool Save(DecompilerTextView textView) { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(key)); if (dlg.ShowDialog() == true) { data.Position = 0; using (var fs = dlg.OpenFile()) { data.CopyTo(fs); } } return true; }
public static void ExportDataGrid(DataGrid dGrid, String author, String companyName, String mergeCells, int boldHeaderRows) { SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = FILE_FILTER, FilterIndex = 2 }; if (objSFD.ShowDialog() == true) { string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper(); Stream outputStream = objSFD.OpenFile(); ExportToExcel(dGrid, author, companyName, mergeCells, boldHeaderRows, strFormat, outputStream); } }
// TODO Fix #else /// <summary> /// Determines the filename of the file what will be used. /// </summary> /// <returns>The <see cref="Stream"/> of the file or <c>null</c> if no file was selected by the user..</returns> /// <remarks> /// If this method returns a valid <see cref="Stream"/> object, the <c>FileName</c> property will be filled /// with the safe filename. This can be used for display purposes only. /// </remarks> public virtual Stream DetermineFile() { var fileDialog = new SaveFileDialog(); fileDialog.Filter = Filter; bool result = fileDialog.ShowDialog() ?? false; if (result) { FileName = fileDialog.SafeFileName; } return result ? fileDialog.OpenFile() : null; }
private void SaveFileMenuItem_Click(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.FileName = filename; Nullable<bool> result = dialog.ShowDialog(); if(result == true) { TextRange range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); range.Save(dialog.OpenFile(), DataFormats.Text); } //range.Save(); }
private void Button_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Pdf file|*.pdf"; if (saveFileDialog1.ShowDialog()==true) { using (FileStream fs = (FileStream)saveFileDialog1.OpenFile()) { byte[] documentBytes = this.CreateDocument(); fs.Write(documentBytes, 0, documentBytes.Length); } } }
private void SaveStyleSheet_Click(object sender, RadRoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Xaml Files|*.xaml"; if (sfd.ShowDialog() == true) { using (var stream = sfd.OpenFile()) { Stylesheet stylesheet = new Stylesheet(); stylesheet.ExtractStylesheetFromDocument(this.editor.Document); XamlFormatProvider.SaveStylesheet(stylesheet, stream); } } }
public override void Execute(object parameter) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PDF file (*.pdf)|*.pdf"; if (saveFileDialog.ShowDialog() == true) { using (Stream saveStream = saveFileDialog.OpenFile()) { documentStream.Seek(0, SeekOrigin.Begin); documentStream.CopyTo(saveStream); documentStream.Flush(); saveStream.Flush(); } } }
private void btnExport_Click(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Export screenshot"; sfd.Filter = "PNG Image (*.png)|*.png"; sfd.FilterIndex = 0; if(sfd.ShowDialog().Value) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imgScreenshot.Source as BitmapSource)); using (var stream = sfd.OpenFile()) encoder.Save(stream); } }
private void btnSave_Click(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Jpeg files (*.jpg)|*.jpg|Png files (*.png)|*.png"; if (sfd.ShowDialog() == true) { using (var stream = sfd.OpenFile()) { if (sfd.SafeFileName.EndsWith(".jpg")) chart.SaveImage(stream, ImageFormat.Jpeg); else chart.SaveImage(stream, ImageFormat.Png); } } }
private void btnBrowse_Click(object sender, RoutedEventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "JSON Files (*.json)|*.json|All Files (*.*)|*.*"; dlg.Title = "JSON Save Location"; dlg.ShowDialog(); if (dlg.FileName != "") { if (outputFile != null) { outputFile.Close(); } outputFile = new StreamWriter(dlg.OpenFile()); txtPath.Text = dlg.FileName; btnExtract.IsEnabled = lstTables.SelectedItems.Count > 0; } }
private static void SaveFile(SaveFileDialog dialog, IDocumentFormatProvider provider, RadDocument document) { var result = dialog.ShowDialog(); if (result == true) { try { using (var stream = dialog.OpenFile()) { provider.Export(document, stream); } } catch (IOException ex) { MessageBox.Show(ex.Message); } } }
private void AsymmetricKeygen_Click(object sender, RoutedEventArgs e) { var password = PromptPassword(); if (password == null) return; var dialog = new SaveFileDialog { Title = "Save Private Key", Filter = "ShomreiTorah Encrypted Private Key File (*.private-key)|*.private-key", FileName = Path.Combine(App.SourceRoot, @"Config", "UpdateKey " + DateTime.Now.ToString("yyyy-MM-dd") + ".private-key") }; if (dialog.ShowDialog() != true) return; using (var stream = dialog.OpenFile()) using (var rsa = new RSACryptoServiceProvider(4096)) { KeyStorage.WriteKey(stream, password, rsa); SetPublicKey(rsa); } }
public static void SaveDocument(Workbook workbook, string selectedFormat) { IWorkbookFormatProvider formatProvider = GetFormatProvider(selectedFormat); if (formatProvider == null) { return; } SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = String.Format("{0} files|*{1}|All files (*.*)|*.*", selectedFormat, formatProvider.SupportedExtensions.First()); if (dialog.ShowDialog() == true) { using (var stream = dialog.OpenFile()) { formatProvider.Export(workbook, stream); } } }
private void Export(System.Windows.Controls.Border element) { PrepareForExport(element); var dialog = new SaveFileDialog { DefaultExt = "pdf", Filter = "Pdf files|*.pdf|All Files (*.*)|*.*", }; if (dialog.ShowDialog() == true) { RadFixedDocument document = this.CreateDocument(element); PdfFormatProvider provider = new PdfFormatProvider(); provider.ExportSettings.ImageQuality = ImageQuality.High; using (var output = dialog.OpenFile()) { provider.Export(document, output); } } }
protected void ExportToImageCommandExecute(object param) { var scheduleView = param as RadScheduleView; scheduleView.MinTimeRulerExtent = scheduleView.ActualHeight - 60; scheduleView.MaxTimeRulerExtent = scheduleView.ActualHeight - 60; SaveFileDialog saveFileDialog = new SaveFileDialog() { DefaultExt = "png", Filter = "PNG (*.png)|*.png" }; if (saveFileDialog.ShowDialog() == true) { using (Stream stream = saveFileDialog.OpenFile()) { ExportExtensions.ExportToImage(scheduleView, stream, new PngBitmapEncoder()); } } }
protected void ExportToXpsCommandExecute(object param) { var scheduleView = param as RadScheduleView; scheduleView.MinTimeRulerExtent = scheduleView.ActualHeight - 60; scheduleView.MaxTimeRulerExtent = scheduleView.ActualHeight - 60; SaveFileDialog saveFileDialog = new SaveFileDialog() { DefaultExt = "xps", Filter = "XPS (*.xps)|*.xps" }; if (saveFileDialog.ShowDialog() == true) { using (Stream stream = saveFileDialog.OpenFile()) { ExportExtensions.ExportToXpsImage(scheduleView, stream); } } }
private void ButtonSaveClick(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Zip File | *.zip"; bool? dialogResult = dialog.ShowDialog(); if (dialogResult == true) { using (ZipArchive zipArchive = new ZipArchive(dialog.OpenFile(), ZipArchiveMode.Create, false, null)) { IEnumerable<DataItem> selectedFiles = items.Where(CheckIsFileSelected); foreach (DataItem file in selectedFiles) { MemoryStream stream = CreateNewFile(file); using (ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(file.FileName)) { Stream entryStream = archiveEntry.Open(); stream.CopyTo(entryStream); } } } } }
private static void InternalSave(Action<C1XLBook> action) { var dlg = new SaveFileDialog(); dlg.Filter = "Excel Files (*.xlsx)|*.xlsx"; if (dlg.ShowDialog() == true) { try { var book = new C1XLBook(); if (action != null) { action(book); } using (var stream = dlg.OpenFile()) { book.Save(stream); } } catch (Exception x) { MessageBox.Show(x.Message); } } }
// What to do when the user wants to export a SVG file private void exportHandler(object sender, EventArgs e) { Stream stream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "SVG files|*.svg"; saveFileDialog.RestoreDirectory = true; if(saveFileDialog.ShowDialog() == DialogResult.OK) { if((stream = saveFileDialog.OpenFile()) != null) { SVGHandler drawhandler = new SVGHandler(); drawhandler.Draw(shapes); using(StreamWriter writer = new StreamWriter(stream)) { foreach (string s in drawhandler.SVGOutput) writer.WriteLine(s); } } } }
private void btnExcel_Click(object sender, EventArgs e) { try { IWorkbook mWorkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); ISheet mSheet = mWorkbook.CreateSheet("Sheet1"); ICellStyle styleRight = mWorkbook.CreateCellStyle(); //ICellStyle NumberStyle = mWorkbook.CreateCellStyle(); //IDataFormat format = mWorkbook.CreateDataFormat(); styleRight.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; styleRight.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //NumberStyle.DataFormat = format.GetFormat("0.00"); ICell mCell; int i, j; DataGridView mView = dgvReport; //添加标头 IRow mRow = mSheet.CreateRow(0); for (i = 0; i <= mView.Columns.Count - 1; i++) { mCell = mRow.CreateCell(i); mCell.SetCellValue(mView.Columns[i].HeaderText); mCell.CellStyle = styleRight; } //添加内容 for (i = 1; i <= mView.RowCount; i++) { mRow = mSheet.CreateRow(i); for (j = 0; j <= mView.Columns.Count - 1; j++) { mCell = mRow.CreateCell(j); if (Classes.PubFunc.IsNumber(Convert.ToString(mView.Rows[i - 1].Cells[j].Value)) == true) { mCell.SetCellValue(Convert.ToDouble(mView.Rows[i - 1].Cells[j].Value)); } else { mCell.SetCellValue(Convert.ToString(mView.Rows[i - 1].Cells[j].Value)); } mCell.CellStyle = styleRight; } } //创建文件 SaveFileDialog mDialog = new SaveFileDialog(); mDialog.AddExtension = true; mDialog.DefaultExt = "xls"; mDialog.Filter = "Excel Worksheets(*.xls)|*.xls"; mDialog.InitialDirectory = System.Environment.CurrentDirectory; mDialog.FileName = "开票信息-" + DateTime.Now.ToString("yyyyMMddhhmmss"); if (mDialog.ShowDialog() == DialogResult.OK) { Stream mFile = mDialog.OpenFile(); mWorkbook.Write(mFile); mFile.Close(); MessageBox.Show("保存成功!", "提示"); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
private void OutPutExcelButton_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl表格文件 (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Excel文件到"; saveFileDialog.ShowDialog(); Stream myStream; try { myStream = saveFileDialog.OpenFile(); } catch (IndexOutOfRangeException) { return; } //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try { //写标题 for (int i = 0; i < this.PatientDataView.ColumnCount; i++) { if (i > 0) { str += "\t"; } str += PatientDataView.Columns[i].HeaderText; } sw.WriteLine(str); //写内容 for (int j = 0; j < PatientDataView.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < PatientDataView.Columns.Count; k++) { if (k > 0) { tempStr += "\t"; } tempStr += (PatientDataView.Rows[j].Cells[k].Value == System.DBNull.Value ? "" : PatientDataView.Rows[j].Cells[k].Value); } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); MessageBox.Show("导出成功"); } catch (Exception e1) { MessageBox.Show(e1.ToString()); } finally { sw.Close(); myStream.Close(); } }
private void btnExcel_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = @"execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = @"保存为Excel文件"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName.IndexOf(":", StringComparison.Ordinal) < 0) { return; //被点了"取消" } Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dgvDressesShow.ColumnCount; i++) { if (i > 0) { columnTitle += "\t"; } columnTitle += dgvDressesShow.Columns[i].HeaderText; } sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dgvDressesShow.Rows.Count; j++) { string columnValue = ""; for (int k = 0; k < dgvDressesShow.Columns.Count; k++) { if (k > 0) { columnValue += "\t"; } object obj = dgvDressesShow.Rows[j].Cells[k].Value; if (obj == null) { columnValue += ""; } else { columnValue += obj.ToString().Trim().Replace("\t", " ").Replace("\r", " ").Replace("\n", " "); } } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); MessageBox.Show(@"成功将数据导出到EXCEL文件中"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); } }
private async void SaveAllGamesToFile(SaveFileDialog fileDialog) { List <SaveGame> currentWatchedGames = new List <SaveGame>(); Uri uri = new Uri("https://blaseball.com"); SocketIO socket = new SocketIO(uri); bool roundStarted = false; bool allCompleted = false; socket.On("gameDataUpdate", (data) => { List <ServerData> serverDataList = JsonConvert.DeserializeObject <List <ServerData> >(data.ToString()); List <Game> games = serverDataList[0].schedule; bool activeGame = !roundStarted; bool indicatorFlipped = false; foreach (Game game in serverDataList[0].schedule) { if (!game.gameComplete && !roundStarted) { roundStarted = true; } //mark round as started, start watching for all games completed if (roundStarted && !activeGame) { activeGame = !game.gameComplete; } //if round has started and no active game found yet, set flag if this game is active if (!game.gameComplete) //if this game is currently active { bool found = false; foreach (SaveGame checkGame in currentWatchedGames) { if (game._id == checkGame._id) { found = true; checkGame.UpdateSaveGame(game); } if (!found) { SaveGame newGame = new SaveGame(game); currentWatchedGames.Add(newGame); } } //UpdateWatchedGame(currentWatchedGames, game); } } allCompleted = !activeGame; if (!indicatorFlipped && roundStarted) { SetText("Recording...", recordIndicator); indicatorFlipped = true; } if (allCompleted) { foreach (SaveGame saveGame in currentWatchedGames) { saveGame.lastUpdate = "Game over."; saveGame.gameComplete = true; } waitHandle.Set(); } }); await socket.ConnectAsync(); waitHandle.WaitOne(); JsonSerializer serializer = new JsonSerializer(); using (Stream fileStreamBytes = fileDialog.OpenFile()) { using (StreamWriter fileStream = new StreamWriter(fileStreamBytes)) { serializer.Serialize(fileStream, currentWatchedGames); } } SetVis(false, recordIndicator); MessageBox.Show("All games completed!"); }
public void gerarPDF(DataGridView dataGrid, string tpRelatorio) { log.logador("Iniciando processo de geração de PDF para relatorio de: " + tpRelatorio); PdfPTable pdfTable = new PdfPTable(dataGrid.ColumnCount); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_CENTER; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row foreach (DataGridViewColumn column in dataGrid.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.BaseColor(250, 250, 250); pdfTable.AddCell(cell); } //Adding DataRow foreach (DataGridViewRow row in dataGrid.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Value != null) { pdfTable.AddCell(cell.Value.ToString()); } else { pdfTable.AddCell(""); } } } String dataRelatorio = Convert.ToString(DateTime.Now); dataRelatorio = dataRelatorio.Replace("/", "-").Replace(":", "-"); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Arquivo|*.pdf"; saveFileDialog1.Title = "Selecione o local para salvar"; saveFileDialog1.FileName = "Relatorio " + tpRelatorio + "-" + dataRelatorio + ".pdf"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); fs.Close(); } String folderPath = Convert.ToString(saveFileDialog1.FileName); using (FileStream stream = new FileStream(folderPath, FileMode.Create)) { Document pdfDoc = new Document(PageSize.A3, 30f, 30f, 30f, 30f); PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); log.logador("PDF de relatorio de: " + tpRelatorio + " gerado com sucesso no diretorio: " + folderPath); } }
public static bool SaveToPickedFile(this BitmapSource bitmap, string defaultFileName = null) { var sfd = new SaveFileDialog { AddExtension = true, DefaultExt = ".png", Filter = "PNG Image|*.png|JPEG Image|*.jpg;*.jpeg|Bitmap Image|*.bmp|TIFF Image|*.tiff" }; if (defaultFileName != null) { sfd.FileName = Path.GetFileNameWithoutExtension(defaultFileName); var dir = Path.GetDirectoryName(defaultFileName); if (dir != null) { sfd.InitialDirectory = dir; } } else { sfd.FileName = "Untitled"; } if (!sfd.ShowDialog().GetValueOrDefault()) { return(false); } BitmapEncoder encoder; // Filter Index starts from 1 switch (sfd.FilterIndex) { case 2: encoder = new JpegBitmapEncoder(); break; case 3: encoder = new BmpBitmapEncoder(); break; case 4: encoder = new TiffBitmapEncoder(); break; default: encoder = new PngBitmapEncoder(); break; } encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (var stream = sfd.OpenFile()) { encoder.Save(stream); } return(true); }
public OperationReturn ExportDataToExecel <T>(List <T> listData, List <ViewColumnInfo> listColumns, UMPApp currentApp) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = 0; try { if (listData == null) { optReturn.Result = false; optReturn.Code = Defines.RET_OBJECT_NULL; optReturn.Message = string.Format("ListData is null"); return(optReturn); } if (listData.Count <= 0) { optReturn.Result = false; optReturn.Code = Defines.RET_NOT_EXIST; optReturn.Message = string.Format("No Record Data"); return(optReturn); } SaveFileDialog dialog = new SaveFileDialog(); dialog.DefaultExt = "xls"; dialog.Filter = "Excel Files (*.xls)|*.xls"; dialog.FilterIndex = 1; dialog.RestoreDirectory = true; if (dialog.ShowDialog() != true) { optReturn.Code = Defines.RET_ALREADY_EXIST; return(optReturn); } StringBuilder sb = new StringBuilder(); List <string> listFields = new List <string>(); int intColCount = listColumns.Count; //列标题 for (int i = 0; i < intColCount; i++) { string strTitle = currentApp.GetLanguageInfo( string.Format("COL{0}{1}", listColumns[i].ViewID, listColumns[i].ColumnName), listColumns[i].ColumnName); listFields.Add(FormatField(strTitle)); } BuildStringToRow(sb, listFields); //列数据 PropertyInfo[] listProperty; PropertyInfo property; for (int i = 0; i < listData.Count; i++) { T item = listData[i]; listFields.Clear(); listProperty = item.GetType().GetProperties(); for (int j = 0; j < intColCount; j++) { ViewColumnInfo column = listColumns[j]; property = listProperty.FirstOrDefault(p => p.Name == column.ColumnName); if (property != null) { var temp = property.GetValue(item, null); if (temp != null) { string strValue; switch (column.ColumnName) { case "Duration": strValue = Converter.Second2Time(Convert.ToDouble(temp)); break; case "StartRecordTime": case "StopRecordTime": strValue = Convert.ToDateTime(temp).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); break; case "Direction": strValue = currentApp.GetLanguageInfo(string.Format("3102TIP001{0}", temp), temp.ToString()); break; default: strValue = temp.ToString(); break; } listFields.Add(FormatField(strValue)); } else { listFields.Add(FormatField(String.Empty)); } } else { listFields.Add(FormatField(string.Empty)); } } BuildStringToRow(sb, listFields); } StreamWriter streamWriter = new StreamWriter(dialog.OpenFile()); streamWriter.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); streamWriter.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>"); streamWriter.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\">"); streamWriter.WriteLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">"); streamWriter.WriteLine("<Author>" + currentApp.Session.UserInfo.Account + "</Author>"); streamWriter.WriteLine("<Created>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</Created>"); streamWriter.WriteLine("<LastSaved>" + DateTime.Now.ToLocalTime().ToLongDateString() + "</LastSaved>"); streamWriter.WriteLine("<Company>" + "VoiceCyber" + "</Company>"); streamWriter.WriteLine("<Version>1.00</Version>"); streamWriter.WriteLine("</DocumentProperties>"); streamWriter.WriteLine("<Worksheet ss:Name=\"UMP Export\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">"); streamWriter.WriteLine("<Table>"); streamWriter.WriteLine(sb); streamWriter.WriteLine("</Table>"); streamWriter.WriteLine("</Worksheet>"); streamWriter.WriteLine("</Workbook>"); streamWriter.Close(); optReturn.Data = dialog.FileName; } catch (Exception ex) { optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; } return(optReturn); }
private void Car_ClacAccessibility_AndSave_Btn_Click(object sender, EventArgs e) { if (bIsloadcarTimematrix == false || bIsloadPopulation == false || bIsloadServiceFacality == false || bIsloadtransitTimematrix == false) { MessageBox.Show("数据输入不完整,无法计算可达性!"); return; } if (TimeMatrix_Car.Count % Hospital_Capacity.Count != 0) { MessageBox.Show("时间矩阵数据输入有误 或 设施数据输入有误!"); return; } Alpha_car = double.Parse(Alpha_car_Text.Text); Beta_car = double.Parse(Beta_car_Text.Text); Alpha_transit = double.Parse(Alpha_transit_text.Text); Beta_transit = double.Parse(Beta_transit_text.Text); Car_minTime = double.Parse(Tmin_car_Text.Text); Car_maxTime = double.Parse(Tmax_car_Text.Text); Transit_minTime = double.Parse(Tmin_transit_text.Text); Transit_maxTime = double.Parse(Tmax_transit_text.Text); ArrayList subDistrict_List = new ArrayList(); ArrayList ServiceFacility_List = new ArrayList(); for (int i = 0; i < TimeMatrix_Car.Count / Hospital_Capacity.Count; i++) { subDistrict temp = new subDistrict();; temp.id = i + 1; temp.population = (double)PopulationList[i]; for (int j = i * Hospital_Capacity.Count; j < (i + 1) * Hospital_Capacity.Count; j++) { temp.CartravelTimes.Add(TimeMatrix_Car[j]); temp.TransittravelTimes.Add(TimeMatrix_Transit[j]); } subDistrict_List.Add(temp); } //////计算供需比 for (int i = 0; i < Hospital_Capacity.Count; i++) { ServiceFacility temp = new ServiceFacility(); temp.capacity = (double)Hospital_Capacity[i]; double demands_Sum = 0; for (int j = 0; j < subDistrict_List.Count; j++) { subDistrict subD = (subDistrict)subDistrict_List[j]; if ((double)subD.CartravelTimes[i] <= Car_maxTime) { demands_Sum += subD.population * double.Parse(Prob_car_Text.Text) * Calc_decayValue((double)subD.CartravelTimes[i], Alpha_car, Beta_car, Car_minTime, Car_maxTime); } if ((double)subD.TransittravelTimes[i] <= Transit_maxTime) { demands_Sum += subD.population * double.Parse(Prob_transit_Text.Text) * Calc_decayValue((double)subD.TransittravelTimes[i], Alpha_transit, Beta_transit, Transit_minTime, Transit_maxTime); } } temp.Supply_demand_ratio = (double)temp.capacity / demands_Sum; ServiceFacility_List.Add(temp); } //计算可达性 for (int i = 0; i < subDistrict_List.Count; i++) { subDistrict subD = (subDistrict)subDistrict_List[i]; for (int j = 0; j < ServiceFacility_List.Count; j++) { if ((double)subD.CartravelTimes[j] <= Car_maxTime) { ServiceFacility sf = (ServiceFacility)ServiceFacility_List[j]; subD.car_Accessibility += (sf.Supply_demand_ratio * Calc_decayValue((double)subD.CartravelTimes[j], Alpha_car, Beta_car, Car_minTime, Car_maxTime)); } if ((double)subD.TransittravelTimes[j] <= Transit_maxTime) { ServiceFacility sf = (ServiceFacility)ServiceFacility_List[j]; subD.transit_Accessibility += (sf.Supply_demand_ratio * Calc_decayValue((double)subD.TransittravelTimes[j], Alpha_transit, Beta_transit, Transit_minTime, Transit_maxTime)); } } subD.multiModal_Accessibility = double.Parse(Prob_car_Text.Text) * subD.car_Accessibility + double.Parse(Prob_transit_Text.Text) * subD.transit_Accessibility; subD.multiModal_Accessibility = double.Parse(Prob_car_Text.Text) * subD.car_Accessibility + double.Parse(Prob_transit_Text.Text) * subD.transit_Accessibility; subDistrict_List[i] = subD; } SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "CSV|*.csv"; saveFileDialog1.Title = "Save an csv File"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); for (int i = 0; i < subDistrict_List.Count; i++) { subDistrict temp = (subDistrict)subDistrict_List[i]; sw.Write(temp.car_Accessibility.ToString() + "," + temp.transit_Accessibility + "," + temp.multiModal_Accessibility + "\n"); } sw.Close(); fs.Close(); } MessageBox.Show("导出完成!"); }
private void BtnCompareChanges_Click(object sender, RoutedEventArgs e) { // Get model from selected item var model = ComboModels.SelectedItem as Model; // Get secureUrl from event as object var latestEventUrl = new Uri(Unifi.GetSecureUrl(_unifiToken, model, LatestCommit.EventId).ToString()); // Set event data from event URL var latestEvent = Unifi.GetEventData(latestEventUrl); // Get latest and selected event families as lists var latestEventFamilies = latestEvent.Data.ProjectFamilies.FamilyInstances.ToList(); var selectedEventFamilies = SelectedEvent.Data.ProjectFamilies.FamilyInstances.ToList(); // Retrieves all of the families that have been added to the project model since the selected sync var addedFamilies = Unifi.GetNewFamilies(selectedEventFamilies, latestEventFamilies); // Retrieves all of the families that have been deleted from the project model since the selected sync var deletedFamilies = Unifi.GetDeletedFamilies(selectedEventFamilies, latestEventFamilies); // Calculate the elapsed time between syncs var elapsedTime = latestEvent.CollectionTime.Subtract(SelectedEvent.CollectionTime); // Store the results of the test in a string var reportData = "# Revit Model Changelog\n"; // Add a summary of data regarding the report reportData += "This report was generated using the UNIFI Project Analytics API. For access to the source code, visit " + "[https://github.com/unifilabs/UNIFI-ProjectAnalytics-API-Sample]." + "\n---\n" + "*Model:* " + (ComboModels.SelectedItem as Model)?.Filename + "\n" + "*Dates Compared:* " + SelectedEvent.CollectionTime.LocalDateTime + " => " + latestEvent.CollectionTime.LocalDateTime + "\n" + "*Time elapsed:* " + elapsedTime.Days + " days, " + elapsedTime.Hours + " hours, " + elapsedTime.Minutes + " minutes, " + elapsedTime.Seconds + " seconds"; reportData += "\n---\n"; // Add the added families to the report string reportData += "## Families Added\n"; // Get number of added families var numberOfAddedFamilies = addedFamilies.Count(); if (numberOfAddedFamilies != 0) { // Create a counter the generate an ordered list var counter = 1; reportData = reportData + ($"{numberOfAddedFamilies:n0}" + " families have been added.\n\n"); // Add an ordered list item for each family in the list foreach (var fam in addedFamilies) { // Write data to a line in the report reportData += counter + ". [" + fam.ElementId + "] " + fam.Name + "\n"; // Increase the counter by one to continue the ordered list counter += 1; } } else { reportData += "No families were added.\n"; } reportData += "\n---\n"; // Add the deleted families to the report string reportData += "## Families Deleted\n"; if (deletedFamilies.Count() != 0) { // Create a counter the generate an ordered list var counter = 1; reportData += $"{deletedFamilies.Count():n0}" + " families have been deleted.\n\n"; // Add an ordered list item for each family in the list foreach (var fam in deletedFamilies) { // Write data to a line in the report reportData += counter + ". [" + fam.ElementId + "] " + fam.Name + "\n"; // Increase the counter by one to continue the ordered list counter += 1; } } else { reportData += "No families were deleted.\n"; } reportData += "\n---\n"; // Save the string as a text file var save = new SaveFileDialog { FileName = "UNIFI Project Analytics Changelog", Filter = "Markdown Text File | *.md" }; if (save.ShowDialog() == true) { var writer = new StreamWriter(save.OpenFile()); writer.Write(reportData); writer.Dispose(); writer.Close(); MessageBox.Show("Report saved to: " + save.FileName); } }
private void Communitypage_calc_Accessibility_Click(object sender, EventArgs e) { ArrayList Community_List = new ArrayList(); for (int i = 0; i < Community_TimeMatrix.Count / Hospital_Capacity.Count; i++) { subDistrict temp = new subDistrict();; temp.id = i + 1; //temp.population = (double)PopulationList[i]; for (int j = i * Hospital_Capacity.Count; j < (i + 1) * Hospital_Capacity.Count; j++) { temp.CartravelTimes.Add(Community_TimeMatrix[j]); } Community_List.Add(temp); } ////test //for(int i = 0; i < populationCell_List.Count;i++) //{ // subDistrict subD = (subDistrict)populationCell_List[i]; // for (int j = 0; j < Facalityclass_List.Count; j++) // { // if ((double)subD.CartravelTimes[j] <= double.Parse(Gadecay_timeThreshold.Text)) // { // ServiceFacility sf = (ServiceFacility)Facalityclass_List[j]; // subD.car_Accessibility += (sf.Supply_demand_ratio * calc_GadecayValue((double)subD.CartravelTimes[j], double.Parse(Gadecay_timeThreshold.Text))); // } // } // populationCell_List[i] = subD;' //} //计算可达性 for (int i = 0; i < Community_List.Count; i++) { subDistrict subD = (subDistrict)Community_List[i]; for (int j = 0; j < Facalityclass_List.Count; j++) { if ((double)subD.CartravelTimes[j] <= double.Parse(Gadecay_timeThreshold.Text)) { ServiceFacility sf = (ServiceFacility)Facalityclass_List[j]; //subD.car_Accessibility += (sf.Supply_demand_ratio * Calc_decayValue((double)subD.CartravelTimes[j], Alpha_car, Beta_car, Car_minTime, Car_maxTime)); subD.car_Accessibility += (sf.Supply_demand_ratio * calc_GadecayValue((double)subD.CartravelTimes[j], double.Parse(Gadecay_timeThreshold.Text))); } //if ((double)subD.TransittravelTimes[j] <= Transit_maxTime) //{ // ServiceFacility sf = (ServiceFacility)ServiceFacility_List[j]; // subD.transit_Accessibility += (sf.Supply_demand_ratio * Calc_decayValue((double)subD.TransittravelTimes[j], Alpha_transit, Beta_transit, Transit_minTime, Transit_maxTime)); //} } //subD.multiModal_Accessibility = double.Parse(Prob_car_Text.Text) * subD.car_Accessibility + double.Parse(Prob_transit_Text.Text) * subD.transit_Accessibility; //subD.multiModal_Accessibility = double.Parse(Prob_car_Text.Text) * subD.car_Accessibility + double.Parse(Prob_transit_Text.Text) * subD.transit_Accessibility; Community_List[i] = subD; } SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "CSV|*.csv"; saveFileDialog1.Title = "Save an csv File"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); for (int i = 0; i < Community_List.Count; i++) { subDistrict temp = (subDistrict)Community_List[i]; sw.WriteLine(temp.car_Accessibility.ToString()); //sw.Write(temp.car_Accessibility.ToString() + "," + temp.transit_Accessibility + "," + temp.multiModal_Accessibility + "\n"); } sw.Close(); fs.Close(); } MessageBox.Show("导出完成!"); }
private void Button_Click_10(object sender, RoutedEventArgs e) { int rozmiar = 0; bool kontynuuj = true; BitArray ziarnoA = new BitArray(N); BitArray ziarnoS = new BitArray(N1); string z = wp.Text; string z2 = wp2.Text; BitArray input; if (z.Length == 0 || długość.Text.Length == 0 || z2.Length == 0) { MessageBox.Show("Brak wystarczających danych. Wartość początkowa rejestru oraz długosć generowanego ciągu powinny być wypełnione "); kontynuuj = false; } if (z.Length != N) { MessageBox.Show("Wielkość wartości poczatkowej rejestru A nie jest zgodna z wielkością rejestru: " + N); kontynuuj = false; } if (z2.Length != N1) { MessageBox.Show("Wielkość wartości poczatkowej rejestru S nie jest zgodna z wielkością rejestru: " + N1); kontynuuj = false; } if (kontynuuj) { rozmiar = Int32.Parse(długość.Text); for (int i = 0; i < z.Length; i++) { if (z[i] == '1') { ziarnoA[i] = true; } if (z[i] == '0') { ziarnoA[i] = false; } else if (z[i] != '0' && z[i] != '1') { MessageBox.Show("Błędne dane.Wartość początkowa rejestru A powinna się składać tylko z 0 i 1."); kontynuuj = false; } } for (int i = 0; i < z2.Length; i++) { if (z2[i] == '1') { ziarnoS[i] = true; } if (z2[i] == '0') { ziarnoS[i] = false; } else if (z2[i] != '0' && z2[i] != '1') { MessageBox.Show("Błędne dane.Wartość początkowa rejestru S powinna się składać tylko z 0 i 1."); kontynuuj = false; } } } input = Rozrzedzający(ziarnoA, ziarnoS, N, N1, rozmiar); byte[] buffer = ToByteArray(input); Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "bin files (.bin)|.bin"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; Nullable <bool> result = saveFileDialog1.ShowDialog(); if (result == true) { if ((myStream = saveFileDialog1.OpenFile()) != null) { myStream.Write(buffer, 0, buffer.Length); myStream.Close(); } } }
public void ExportFileAutomod() { var automodInitCode = "begin model initialization function" + "\r\n //Define all A_* as integer attributes" + "\r\n //Define all Vs as string variables" + "\r\n set Q_ExportBlocking capacity to 1" + "\r\n print \"OpenSource command (0=OK): \" DBOpenSourceUDL(\"connectdb.udl\",\"connectdb\")to message\r\n print \"OpenSession command (0=OK): \" DBOpenSession(\"connectdb\",\"first\")to message" + "\r\n print \"Delete from [ProductResult]\" to Vs_sqlCommand" + "\r\n print \"Executing command (0=OK): \" DBExecuteCmd(\"first\", Vs_sqlCommand) to message" + "\r\n print \"Delete from [MachineStates]\" to Vs_sqlCommand" + "\r\n print \"Executing command (0=OK): \" DBExecuteCmd(\"first\", Vs_sqlCommand) to message" + "\r\n create 1 loads of load type L_Dummy to P_TerminateModel"; var automodProductCode = ""; var automodProductInitProcedures = ""; var automodProductExportData = "\r\nbegin P_ExportFunction arriving procedure" + "\r\n move into Q_ExportBlocking"; var includedModelNodes = new HashSet <ModelNode>(); foreach (var product in ProductList) { if (product.IsChecked ?? false) { automodInitCode += "\r\n create 1 loads of load type L_" + product.ProductName + " to P_" + product.ProductName + "Init"; automodProductInitProcedures += "\r\nbegin P_" + product.ProductName + "Init arriving procedure\r\n" + " wait for 1 sec\r\n" + " while(1=1) begin\r\n create 1 loads of load type L_" + product.ProductName + " to P_" + product.ProductName + "\r\n" + " wait to be ordered on OL_" + product.ProductName + "Init" + "\r\n end\r\nend\r\n"; automodProductCode += "\r\n" + product.AutomodCodeBody(); foreach (var node in product.Nodes) { includedModelNodes.Add(node.Key); } } } automodInitCode += "\r\n //Define V_ExportArray as integer array variable with dimension 1 x " + includedModelNodes.Count; var exportNodeStates = ""; var exported = new HashSet <ModelNode>(); var initiated = new HashSet <ModelNode>(); foreach (var includedModelNode in includedModelNodes) { exportNodeStates += "\r\n print \"INSERT INTO [MachineStates] ([Machine], [State] ,[Total]) VALUES('" + includedModelNode.ResourceModel.ProcessName + "'," + "'Down', \" (rc * R_" + includedModelNode.ResourceModel.ProcessName + " average down) \");\" to Vs_sqlCommand" + "\r\n print \"(0=OK):\" DBExecuteCmd(\"first\", Vs_sqlCommand) to message" + "\r\n print \"INSERT INTO [MachineStates] ([Machine], [State] ,[Total]) VALUES('" + includedModelNode.ResourceModel.ProcessName + "'," + "'IdleTime', \" (rc * (1-R_" + includedModelNode.ResourceModel.ProcessName + " average)) \");\" to Vs_sqlCommand" + "\r\n print \"(0=OK):\" DBExecuteCmd(\"first\", Vs_sqlCommand) to message"; if (!initiated.Contains(includedModelNode)) { automodInitCode += includedModelNode.AutomodInit(includedModelNodes, initiated); } automodProductCode += "\r\n" + includedModelNode.AutoModBreakdownProcess(); //automodProductExportData += "\r\n set V_ExportArray(" + nodenumber++ + ") to A_" + // includedModelNode.ResourceModel.ResultId + "NodeTotal"; automodProductExportData += AutomodProductExportData(exported, includedModelNode); } //automodProductExportData += "\r\n call XLSetArea(\"[Output.xlsx]Sheet1\",\"A1:A" + (nodenumber-1) + "\",\"V_ExportArray\")" + automodProductExportData += "\r\nend"; automodInitCode += "\r\n return 0\r\nend" + "\r\n " + "\r\nbegin P_TerminateModel arriving procedure" + "\r\n wait for " + SimulationTimeConverted / 3600000 + " hr" + "\r\n wait for V_SnapLength sec" + "\r\n print \"INSERT INTO [MachineStates] ([Machine], [State] ,[Total]) VALUES('BaseModel'," + "'BaseTime', \" rc \");\" to Vs_sqlCommand" + "\r\n print \"(0=OK):\" DBExecuteCmd(\"first\", Vs_sqlCommand) to message" + exportNodeStates + "\r\n call DBCloseSource(\"\")" + "\r\n terminate" + "\r\nend" + "\r\n" + "\r\nbegin model snap function" + "\r\n if V_SnapLength = 0 begin" + "\r\n set V_SnapLength = rc" + "\r\n print \"Delete from [ProductResult]\" to Vs_sqlCommand" + "\r\n print \"Executing command (0=OK): \" DBExecuteCmd(\"first\", Vs_sqlCommand) to message" + "\r\n end" + "\r\n return 1" + "\r\nend"; var save = new SaveFileDialog(); save.AddExtension = true; save.DefaultExt = ".m"; save.FileName = "logic"; save.Filter = "logic file (.m)|*.m"; var result = save.ShowDialog(); if (result == true) { var file = save.OpenFile(); Encoding winLatinCodePage = Encoding.GetEncoding(1252); Byte[] bytes = Encoding.Convert(Encoding.ASCII, winLatinCodePage, Encoding.UTF8.GetBytes(automodInitCode)); Byte[] bytes2 = Encoding.Convert(Encoding.ASCII, winLatinCodePage, Encoding.UTF8.GetBytes(automodProductInitProcedures)); Byte[] bytes3 = Encoding.Convert(Encoding.ASCII, winLatinCodePage, Encoding.UTF8.GetBytes(automodProductCode)); Byte[] bytes4 = Encoding.Convert(Encoding.ASCII, winLatinCodePage, Encoding.UTF8.GetBytes(automodProductExportData)); file.Write(bytes, 0, bytes.Length); file.Write(bytes2, 0, bytes2.Length); file.Write(bytes3, 0, bytes3.Length); file.Write(bytes4, 0, bytes4.Length); file.Close(); var encoding = new System.Text.UnicodeEncoding(); string s = "[oledb]" + Environment.NewLine + "; Everything after this line is an OLE DB initstring" + Environment.NewLine + "Provider=Microsoft.SQLSERVER.CE.OLEDB.4.0;Data Source="; try { s += ApplicationDeployment.CurrentDeployment.DataDirectory + "\\Resources\\modeloutput.sdf;" + Environment.NewLine; } catch { s += Environment.CurrentDirectory + "\\Resources\\modeloutput.sdf;" + Environment.NewLine; } var fileinfo = new FileInfo(save.FileName); string folder = fileinfo.Directory + "\\connectdb.udl"; var bytes5 = new List <byte>(StrToByteArray(s)); bytes5.Insert(0, 254); bytes5.Insert(0, 255); var fi = new FileInfo(folder); if (fi.Exists) { fi.Delete(); } file = new FileStream(folder, FileMode.OpenOrCreate, FileAccess.ReadWrite); file.Write(bytes5.ToArray(), 0, bytes5.Count); file.Close(); } }
/// <summary> /// Copies the current image to the selected file in /// Emf (vector), or a variety of Bitmap formats. /// </summary> /// <param name="DefaultFileName"> /// Accepts a default file name for the file dialog (if "" or null, default is not used) /// </param> /// <returns> /// The file name saved, or "" if cancelled. /// </returns> /// <remarks> /// Note that <see cref="SaveAsBitmap" /> and <see cref="SaveAsEmf" /> methods are provided /// which allow for Bitmap-only or Emf-only handling of the "Save As" context menu item. /// </remarks> public String SaveAs(String DefaultFileName) { if (_masterPane != null) { SaveFileDialog.Filter = "Emf Format (*.emf)|*.emf|" + "PNG Format (*.png)|*.png|" + "Gif Format (*.gif)|*.gif|" + "Jpeg Format (*.jpg)|*.jpg|" + "Tiff Format (*.tif)|*.tif|" + "Bmp Format (*.bmp)|*.bmp"; if (DefaultFileName != null && DefaultFileName.Length > 0) { String ext = System.IO.Path.GetExtension(DefaultFileName).ToLower(); switch (ext) { case ".emf": SaveFileDialog.FilterIndex = 1; break; case ".png": SaveFileDialog.FilterIndex = 2; break; case ".gif": SaveFileDialog.FilterIndex = 3; break; case ".jpeg": case ".jpg": SaveFileDialog.FilterIndex = 4; break; case ".tiff": case ".tif": SaveFileDialog.FilterIndex = 5; break; case ".bmp": SaveFileDialog.FilterIndex = 6; break; } //If we were passed a file name, not just an extension, use it if (DefaultFileName.Length > ext.Length) { SaveFileDialog.FileName = DefaultFileName; } } if (SaveFileDialog.ShowDialog() == DialogResult.OK) { Stream myStream = SaveFileDialog.OpenFile(); if (myStream != null) { if (SaveFileDialog.FilterIndex == 1) { myStream.Close(); SaveEmfFile(SaveFileDialog.FileName); } else { ImageFormat format = ImageFormat.Png; switch (SaveFileDialog.FilterIndex) { case 2: format = ImageFormat.Png; break; case 3: format = ImageFormat.Gif; break; case 4: format = ImageFormat.Jpeg; break; case 5: format = ImageFormat.Tiff; break; case 6: format = ImageFormat.Bmp; break; } ImageRender().Save(myStream, format); //_masterPane.GetImage().Save( myStream, format ); myStream.Close(); } return(SaveFileDialog.FileName); } } } return(""); }
private void btnSave_Click(object sender, EventArgs e) { Stream projFileStream; Templates.ProjectTemplate projectFile = new Templates.ProjectTemplate(); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Project File (*.sap)|*.sap"; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((projFileStream = saveFileDialog1.OpenFile()) != null) { gamePath = GetSystemPath(); XmlSerializer serializer = new XmlSerializer(typeof(Templates.ProjectTemplate)); XmlWriter writer = XmlWriter.Create(projFileStream, new XmlWriterSettings() { Indent = true }); Templates.ProjectInfo projInfo = new Templates.ProjectInfo();; switch (game) { case "sadx": projInfo.GameName = "SADXPC"; projInfo.CanBuild = true; projInfo.ProjectFolder = projPath; List <Templates.SplitEntry> dxsplitEntries = new List <Templates.SplitEntry>() { new Templates.SplitEntry { SourceFile = (sonic + ".exe"), IniFile = (sonic + "_data.ini"), CmnName = "Executable Data" }, new Templates.SplitEntry { SourceFile = (chrmodels + "_orig.dll"), IniFile = (chrmodels + "_orig_data.ini"), CmnName = "Chrmodels Data" }, new Templates.SplitEntry { SourceFile = (adv00models + ".dll"), IniFile = (adv00models + "_data.ini"), CmnName = "Station Square Data" }, new Templates.SplitEntry { SourceFile = (adv01models + ".dll"), IniFile = (adv01models + "_data.ini"), CmnName = "Egg Carrier (Exterior) Data" }, new Templates.SplitEntry { SourceFile = (adv01cmodels + ".dll"), IniFile = (adv01cmodels + "_data.ini"), CmnName = "Egg Carrier (Interior) Data" }, new Templates.SplitEntry { SourceFile = (adv02models + ".dll"), IniFile = (adv02models + "_data.ini"), CmnName = "Mystic Ruins Data" }, new Templates.SplitEntry { SourceFile = (adv03models + ".dll"), IniFile = (adv03models + "_data.ini"), CmnName = "The Past Data" }, new Templates.SplitEntry { SourceFile = (bosschaos0models + ".dll"), IniFile = (bosschaos0models + "_data.ini"), CmnName = "Boss Chaos 0 Data" }, new Templates.SplitEntry { SourceFile = (chaostggarden02mr_daytime + ".dll"), IniFile = (chaostggarden02mr_daytime + "_data.ini"), CmnName = "MR Garden (Daytime) Data" }, new Templates.SplitEntry { SourceFile = (chaostggarden02mr_evening + ".dll"), IniFile = (chaostggarden02mr_evening + "_data.ini"), CmnName = "MR Garden (Evening) Data" }, new Templates.SplitEntry { SourceFile = (chaostggarden02mr_night + ".dll"), IniFile = (chaostggarden02mr_night + "_data.ini"), CmnName = "MR Garden (Night) Data" }, }; projectFile.GameInfo = projInfo; projectFile.SplitEntries = dxsplitEntries; break; case "sa2": projInfo.GameName = "SA2PC"; projInfo.CanBuild = true; projInfo.ProjectFolder = projPath; List <Templates.SplitEntry> sa2splitEntries = new List <Templates.SplitEntry>() { new Templates.SplitEntry { SourceFile = (sonic2app + ".exe"), IniFile = (sonic2app + "_data.ini"), CmnName = "Executable Data" }, new Templates.SplitEntry { SourceFile = (data_dll + "_orig.dll"), IniFile = (data_dll + "_orig_data.ini"), CmnName = "Data DLL Data" }, }; projectFile.GameInfo = projInfo; projectFile.SplitEntries = sa2splitEntries; projectFile.SplitMDLEntries = splitMdlEntries; break; } serializer.Serialize(writer, projectFile); projFileStream.Close(); } } DialogResult xmlCreated = MessageBox.Show(("Project XML Successfully Created!"), "Project XML Created", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); if (xmlCreated == DialogResult.OK) { this.Close(); } }
private void DataGridViewToCSV() { if (dataGridView1.Rows.Count == 0) { MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "CSV files (*.csv)|*.csv"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.FileName = null; saveFileDialog.Title = "保存"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { Stream stream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0)); string strLine = ""; try { //表头 for (int i = 0; i < dataGridView1.ColumnCount; i++) { if (i > 0) { strLine += ","; } strLine += dataGridView1.Columns[i].HeaderText; } strLine.Remove(strLine.Length - 1); sw.WriteLine(strLine); strLine = ""; //表的内容 for (int j = 0; j < dataGridView1.Rows.Count; j++) { strLine = ""; int colCount = dataGridView1.Columns.Count; for (int k = 0; k < colCount; k++) { if (k > 0 && k < colCount) { strLine += ","; } if (dataGridView1.Rows[j].Cells[k].Value == null) { strLine += ""; } else { string cell = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim(); //防止里面含有特殊符号 cell = cell.Replace("\"", "\"\""); cell = "\"" + cell + "\""; strLine += cell; } } sw.WriteLine(strLine); } sw.Close(); stream.Close(); MessageBox.Show("数据被导出到:" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
/// <summary> /// output all the changes made with the editor to a new datadict file /// </summary> private void SaveAs_Execute() { //make sure all the elements that may hold old data before starting the file output process SaveAsOutput.Clear(); SaveAsAttributeDescription.Clear(); SaveAsFinalData.Clear(); //store the header of the currently open file for later use SaveAsOutput = OpenFileBytes.Skip(0).Take(16 + (DDObjects.Count * 8)).ToList(); //for every datadict object in the current file for (int i = 0; i < DDObjects.Count; i++) { ObservableCollection <DataDict_Attribute> SaveAsAttributes = new ObservableCollection <DataDict_Attribute>(DDObjects[i].DataDictObjects); //define the attributes associated to the current data dict object int SaveAsNumAttributes = DDObjects[i].NumOfAttributes; // loop through all atrributes, save to the output attribute description list and final data list for (int a = 0; a < SaveAsNumAttributes; a++) { //add the attributes description the the attribute description array SaveAsAttributeDescription.AddRange(DDObjects[i].DataDictObjects[a].Description.ToList <byte>()); //Set the new offset based on the current length of the final data block and write it to the attribute description array byte[] cbytes = BitConverter.GetBytes(SaveAsFinalData.Count); SaveAsAttributeDescription.AddRange(cbytes.Skip(0).Take(3).ToList()); //write the attribute type to the attribute description array SaveAsAttributeDescription.Add(DDObjects[i].DataDictObjects[a].Type); //based on the attribute type write the appropriate value bytes to the attribute description array if (DDObjects[i].DataDictObjects[a].Type == 13) { SaveAsFinalData.AddRange(ReturnZeroPaddedString(DDObjects[i].DataDictObjects[a].Value)); } else { SaveAsFinalData.AddRange(DDObjects[i].DataDictObjects[a].Value); } } } //add the attribute description array to the final output array SaveAsOutput.AddRange(SaveAsAttributeDescription); //add the final data array to the final output array SaveAsOutput.AddRange(SaveAsFinalData); //update bytes 12-16 to represent the new length of data byte[] newdatalength = BitConverter.GetBytes(SaveAsFinalData.Count); //update the output bytes 4-8 with the new datablock length UpdateDatablockLength(newdatalength); //prepare to write the changes to a file by creating a new savefiledialog SaveFileDialog saveFileDialog1 = new SaveFileDialog(); //Set the window options to default to .datadict file format saveFileDialog1.Filter = "DeathSpank Data Files (*.datadict)| *.datadict"; //set the save as window title saveFileDialog1.Title = "Save a DeathSpank Data File"; //display the save as dialog option saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { //Create a new filestream from the open file dialog options using (FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile()) { //create a binary writer to write to the filestream BinaryWriter bw = new BinaryWriter(fs); //Write data to the new file bw.Write(SaveAsOutput.ToArray()); //flush and close the binarywriter bw.Flush(); bw.Close(); } } }
private void btnExportExcel_Click(object sender, RoutedEventArgs e) { DateTime second = new DateTime(Convert.ToInt32(date2.SelectedDate.Value.ToString("yyyy")), Convert.ToInt32(date2.SelectedDate.Value.ToString("MM")), Convert.ToInt32(date2.SelectedDate.Value.ToString("dd")), 23, 59, 59); try { if (DG_Income.Items.Count > 0) { Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "EXCELL FILE (*.xlsx)|*.xlsx"; saveFileDialog1.RestoreDirectory = true; string filename; if (saveFileDialog1.ShowDialog() == true) { if ((myStream = saveFileDialog1.OpenFile()) != null) { // Code to write the stream goes here. filename = saveFileDialog1.FileName; myStream.Close(); var workbook = new XLWorkbook(); IXLWorksheet worksheet = workbook.Worksheets.Add("Sheet1"); worksheet.Columns().AdjustToContents(); worksheet.Cell(1, 1).Value = "Отчет рабочего " + combWorker.SelectedItem + " с " + date1.SelectedDate + " по " + second; worksheet.Cell(1, 1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); worksheet.Range(worksheet.Cell(1, 1), worksheet.Cell(1, 6)).Merge(); worksheet.Cell(2, 1).Value = "Цена товара"; worksheet.Cell(2, 3).Value = "Наличными"; worksheet.Cell(2, 4).Value = "В пластику"; worksheet.Cell(2, 5).Value = "В долгу"; worksheet.Cell(2, 6).Value = "Из долга"; worksheet.Cell(2, 7).Value = "Возврат"; worksheet.Cell(2, 8).Value = "Дата"; int kk = 3; foreach (Income rv in DG_Income.Items) { worksheet.Cell(kk, 1).Value = rv.SaleProductPrice; worksheet.Cell(kk, 2).Value = rv.CashIncome; worksheet.Cell(kk, 3).Value = rv.PlasticIncome; worksheet.Cell(kk, 4).Value = rv.DebtOut; worksheet.Cell(kk, 5).Value = rv.DebtIncome; worksheet.Cell(kk, 6).Value = rv.Vozvrat; worksheet.Cell(kk, 7).Value = rv.DateTimeNow; kk++; } worksheet.Columns("A", "Z").AdjustToContents(); workbook.SaveAs(filename); Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.StandardInput.WriteLine(filename); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); cmd.WaitForExit(); // workbook. } } } } catch (Exception err) { MessageBox.Show("Error8"); } }
private void SaveFile_Button(object sender, RoutedEventArgs e) { //add new if (radioSelection == RadioSelection.Add) { if (clients.Contains(addCustID.CustomerID.Text)) { ShowDuplicateClientError(); return; } int val; if (!Int32.TryParse(addCustID.CustomerID.Text, out val)) { MessageBox.Show("Sorry, the lottery id must be a number"); return; } } Stream myStream; SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = "JSON Files (*.json)|*.json"; if (saveFile.ShowDialog() == true) { if ((myStream = saveFile.OpenFile()) != null) { string currEditedClientName = (updateCust == null) ? "" : updateCust.UpdateCustBox.SelectedValue.ToString(); string json = (radioSelection == RadioSelection.Translate) ? GetTranslatedFileContent() : GetEditedFileContent(currEditedClientName); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json); myStream.Write(bytes, 0, bytes.Length); myStream.Flush(); myStream.Close(); //if they save it to a new file, open that file if (radioSelection != RadioSelection.Update) { fullPath = saveFile.FileName; currDir = Path.GetDirectoryName(fullPath); fileName = Path.GetFileNameWithoutExtension(fullPath); clients.Clear(); clients.Add(DEFAULT_CLIENT); custIDs.Clear(); ReadJsonFromFile(fullPath); PopulateClientIDs(); updateCust = new UpdateCustomer(this); updateCust.UpdateCustBox.ItemsSource = custIDs; updateCust.UpdateCustBox.SelectedIndex = 0; AddUserControlStep3(updateCust); addCustID = new AddCustomer(); AddUserControlStep3(addCustID); } if (currEditedClientName.Equals("")) { currEditedClientName = DEFAULT_CLIENT; } ReloadCurrentLottery(currEditedClientName); StkEditableValues.Children.Clear(); } //Clear Radio Buttons and user controls foreach (RadioButton child in RadioButtons.Children) { child.IsChecked = false; radioSelection = RadioSelection.Nothing; } Step3.Children.Clear(); } }
public static void createIpsFromCSV(int nRegisters, int sizeRegisters, int address, Dictionary <String, Byte> inputTBL) { List <String> inputStr = CSV_Manager.openFixedSizedTableCSV(); if (inputStr.Count != nRegisters) { return; } List <Byte> byteStream = new List <Byte>(); Byte addressL = (Byte)((address >> 0x00) & 0x0000FF); Byte addressM = (Byte)((address >> 0x08) & 0x0000FF); Byte addressH = (Byte)((address >> 0x10) & 0x0000FF); Byte sizeL = (Byte)(((nRegisters * sizeRegisters) >> 0x00) & 0x0000FF); Byte sizeH = (Byte)(((nRegisters * sizeRegisters) >> 0x08) & 0x0000FF); byteStream.Add(0x50); //P byteStream.Add(0x41); //A byteStream.Add(0x54); //T byteStream.Add(0x43); //C byteStream.Add(0x48); //H byteStream.Add(addressH); //address H byteStream.Add(addressM); //address M byteStream.Add(addressL); //address L byteStream.Add(sizeH); //size H byteStream.Add(sizeL); //size L foreach (String item in inputStr) { byteStream.AddRange(parseStringList(item, inputTBL, sizeRegisters)); //Byte table } byteStream.Add(0x45); //E byteStream.Add(0x4F); //O byteStream.Add(0x46); //F SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "IPS File|*.ips"; saveFileDialog.Title = "Choose a IPS file"; saveFileDialog.FileName = "newTable" + address.ToString("X6"); /* Show the Dialog */ if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (saveFileDialog.FileName != "") { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog.OpenFile(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs); try { bw.Write(byteStream.ToArray()); } catch (Exception e) { MessageBox.Show("Error writing the file: \r\n" + e.ToString(), "Error"); } bw.Close(); fs.Close(); } } }
/// 将DataGridView中的数据保存到exl中,用流保存成xls文件. 这种方法比较好,不用引用Excel组件. /// /// DataGridView public static void DataTableToExl(DataGridView _DataGridView) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出数据到本地计算机"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName == "") { return; } Stream myStream; myStream = saveFileDialog.OpenFile(); //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string str = ""; try { //写标题 for (int i = 0; i < _DataGridView.ColumnCount; i++) { if (i > 0) { str += "\t"; } str += _DataGridView.Columns[i].HeaderText; } sw.WriteLine(str); //写内容 for (int j = 0; j < _DataGridView.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < _DataGridView.Columns.Count; k++) { if (k > 0) { tempStr += "\t"; } if (_DataGridView.Columns[k].HeaderText == "日期") { tempStr += Convert.ToDateTime(_DataGridView.Rows[j].Cells[k].Value).ToString("yyyy-MM-dd"); } else { tempStr += _DataGridView.Rows[j].Cells[k].Value.ToString(); } } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); if (MessageBox.Show("导出成功!你想打开这个文件吗?", "导出到...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = saveFileDialog.FileName; process.StartInfo.Verb = "Open"; process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; process.Start(); } catch { MessageBox.Show("你的计算机中未安装Excel,不能打开该文档!"); } } } }
/// <summary> /// "Generate Status Information..." button handler /// </summary> private void buttonC2V_Click(object sender, System.EventArgs e) { // create an "Save As" dialog instance. SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Title = "Save Generated Status Information As"; saveDialog.Filter = "Customer To Vendor Files (*.c2v)|*.c2v|All Files (*.*)|*.*"; saveDialog.FilterIndex = 1; saveDialog.DefaultExt = "c2v"; saveDialog.FileName = "Dog_demo.c2v"; if (DialogResult.OK != saveDialog.ShowDialog()) { return; } LockDialog = true; // get the update information from SuperDog DogDemoC2v c2v = new DogDemoC2v(this.textHistory); string info = c2v.RunDemo(); LockDialog = false; if (0 == info.Length) { return; } try { // save the info in a file Stream stream = saveDialog.OpenFile(); if (null == stream) { MessageBox.Show(this, "Failed to save file \"" + saveDialog.FileName + "\".", "Save Generated Status Information", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StreamWriter writer = new StreamWriter(stream); writer.Write(info); writer.Close(); stream.Close(); WriteToTextbox(textHistory, "Status Information written to: \"" + saveDialog.FileName + "\"\r\n"); } catch (Exception) { MessageBox.Show(this, "Failed to save file.", "Save Generated Status Information", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnCreateCsv_Click(object sender, EventArgs e) { string fName; string query = @"SELECT DISTINCT ed.extPerson.Id, ed.extPerson.PersonNum as regnum, ed.extPerson.Surname, ed.extPerson.Name, ed.extPerson.SecondName, CAST((STR( DAY( ed.extPerson.Birthdate ) ) + '/' +STR( MONTH( ed.extPerson.Birthdate ) ) + '/' +STR( YEAR( ed.extPerson.Birthdate )))AS DATETIME) as birthdate "; // если по выбрана конкр. ауд. if (ExamVedRoomId != null) { query += " FROM ed.extPerson INNER JOIN ed.ExamsVedRoomHistory ON ed.ExamsVedRoomHistory.PersonId = ed.extPerson.Id " + string.Format("WHERE ed.ExamsVedRoomHistory.ExamsVedRoomId = '{0}' ", ExamVedRoomId.ToString()); fName = cbExamVed.Text + ", " + cbExamVedRoom.Text; } else if (ExamVedId != null) { query += " FROM ed.extPerson INNER JOIN ed.ExamsVedHistory ON ed.ExamsVedHistory.PersonId = ed.extPerson.Id " + string.Format("WHERE ed.ExamsVedHistory.ExamsVedId = '{0}' ", ExamVedId.ToString()); fName = cbExamVed.Text; } else { return; } try { fName = fName.Replace("/", "_"); fName = fName.Replace(":", "-"); SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = fName + ".csv"; sfd.Filter = "CSV files|*.csv"; if (sfd.ShowDialog() != DialogResult.OK) { return; } using (StreamWriter writer = new StreamWriter(sfd.OpenFile(), Encoding.GetEncoding(1251))) { DataSet dsExam = bdc.GetDataSet(string.Format(@"SELECT ed.extExamsVed.Id, ed.extExamsVed.Number, ed.extExamsVed.Date AS ExamDate, ed.extExamsVed.ExamName FROM ed.extExamsVed WHERE ed.extExamsVed.Id = '{0}'", ExamVedId.ToString())); DataRow dr = dsExam.Tables[0].Rows[0]; // если есть разделение по аудиториям, то получим его DataSet dsAudAbits = bdc.GetDataSet(string.Format(@"SELECT ed.ExamsVedHistory.PersonId, ed.ExamsVedRoom.RoomNumber, ed.extPerson.Num FROM ed.ExamsVedHistory LEFT OUTER JOIN ed.ExamsVedRoomHistory ON ed.ExamsVedRoomHistory.PersonId = ed.ExamsVedHistory.PersonId LEFT OUTER JOIN ed.ExamsVedRoom ON ed.ExamsVedRoomHistory.ExamsVedRoomId = ed.ExamsVedRoom.Id INNER JOIN ed.extPerson ON ed.extPerson.Id = ed.ExamsVedHistory.PersonId WHERE ed.ExamsVedHistory.ExamsVedId = '{0}'", ExamVedId.ToString())); List <string> list = new List <string>(); list.Add(dr["ExamName"].ToString()); list.Add(dr["Number"].ToString()); list.Add(DateTime.Parse(dr["ExamDate"].ToString()).ToString("dd/MM/yyyy")); writer.WriteLine(string.Join("%", list.ToArray())); DataSet ds = MainClass.Bdc.GetDataSet(query); foreach (DataRow row in ds.Tables[0].Rows) { list = new List <string>(); list.Add(row["regnum"].ToString()); list.Add(row["surname"].ToString()); list.Add(row["name"].ToString()); list.Add(row["secondname"].ToString()); list.Add(DateTime.Parse(row["birthdate"].ToString()).ToString("dd/MM/yyyy")); string audNum = ( from DataRow x in dsAudAbits.Tables[0].Rows where x["Num"].ToString() == row["regnum"].ToString() select x["RoomNumber"].ToString() == "" ? "общ" : x["RoomNumber"].ToString() ).DefaultIfEmpty <string>("н.указ").ToList <string>()[0]; list.Add(audNum); writer.WriteLine(string.Join("%", list.ToArray())); } } } catch (Exception exc) { WinFormsServ.Error("Ошибка при экспорте: " + exc.Message); } }
// no public static void SavePara(ZedGraghUtils des, ZedGraghUtils tem, SerialPortConfig ser, ZedGraghUtils drg, SaveFileDialog saveFileDialog) { saveFileDialog.FilterIndex = 1; saveFileDialog.Filter = ParaSaveFilter; saveFileDialog.RestoreDirectory = true; if (saveFileDialog.ShowDialog() == DialogResult.OK) { System.IO.FileStream fst = (System.IO.FileStream)saveFileDialog.OpenFile(); //输出文件 fst.Close(); var savePath = saveFileDialog.FileName.ToString(); //获得文件路径 try { FileStream fs = new FileStream(savePath, FileMode.Create); BinaryWriter w = new BinaryWriter(fs); w.Write(des.YMax); w.Write(des.YMin); w.Write(des.DataUp); w.Write(des.DataDown); w.Write(tem.YMax); w.Write(tem.YMin); w.Write(tem.DataUp); w.Write(tem.DataDown); w.Write(ser.BaudRateIndex); w.Write(ser.StopBitsIndex); w.Write(ser.DataBitsIndex); w.Write(ser.ParityIndex); w.Write(ser.BiaoAddressValue); w.Write(ser.ProLinkPath); w.Write(ser.DesValueAddress); w.Write(ser.TemValueAddress); w.Write(ser.K0Value); w.Write(ser.K1Value); w.Write(ser.K2Value); w.Write(ser.ProtocolIndex); w.Write(ser.DesUnitsSelectIndex); w.Write(ser.TemUnitsSelectIndex); w.Write(drg.YMax); w.Write(drg.YMin); w.Write(drg.DataUp); w.Write(drg.DataDown); w.Flush(); w.Close(); fs.Close(); MessageBox.Show("保存参数成功!"); } catch (Exception ex) { throw (ex); } } }
private void SaveAsFile() { lnkFileContextMenu = new ContextMenuStrip(); lnkFile.ContextMenuStrip = lnkFileContextMenu; lnkFileContextMenu.Items.Clear(); lnkFileContextMenu.Items.Add("Lưu file", ThemeUtils.Image16.Images["SAVE"]).Click += delegate { try { bool allow = false; foreach (var i in (FieldUtils.GetModuleFields( ModuleInfo.ModuleID, CODES.DEFMODFLD.FLDGROUP.PARAMETER))) { strFLDID = i.FieldName; allow = true; } if (allow) { var fields = FieldUtils.GetModuleFields(ModuleInfo.ModuleID, CODES.DEFMODFLD.FLDGROUP.PARAMETER); List <string> values = new List <string>(); string StoreName; if (MaintainInfo.Approve == CODES.MODMAINTAIN.APROVE.YES && !string.IsNullOrEmpty(Program.txnum)) { values.Add(Program.txnum); StoreName = "sp_tllog_file_sel"; } else { foreach (var field in fields) { values.Add(this[field.FieldID].ToString()); } StoreName = MaintainInfo.ReportStore; } // End TuanLM if (values.Count > 0) { using (var ctrlSA = new SAController()) { DataContainer container = null; ctrlSA.ExecuteProcedureFillDataset(out container, StoreName, values); if (container != null && container.DataTable != null) { var resultTable = container.DataTable; if (resultTable.Rows.Count > 0) { for (int i = 0; i <= resultTable.Rows.Count - 1; i++) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream((Byte[])resultTable.Rows[i]["filestore"])) { StreamReader memoryReader = new StreamReader(ms); SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = resultTable.Rows[i]["filename"].ToString(); dlg.Filter = resultTable.Rows[i]["filetype"].ToString(); if (dlg.ShowDialog() == DialogResult.OK) { ms.WriteTo(dlg.OpenFile()); } } } ; } else { throw ErrorUtils.CreateError(ERR_FILE.ERR_FILE_IS_NOT_ATTACKED); } } } } } else { throw ErrorUtils.CreateError(ERR_FILE.ERR_FILE_IS_NOT_ATTACKED); } } catch (Exception ex) { ShowError(ex); } }; }
private void ExportToolStripMenuItem_Click(object sender, EventArgs e) { //ToolTipText is the full filename var fileName = ((ToolStripMenuItem)sender).ToolTipText; var tag = ((ToolStripMenuItem)sender).Tag as ExportData; var resource = tag.Resource; Console.WriteLine($"Export requested for {fileName}"); string[] extensions = null; switch (resource.ResourceType) { case ResourceType.Sound: //WAV or MP3 extensions = new[] { ((Sound)resource.Blocks[BlockType.DATA]).Type.ToString().ToLower() }; break; case ResourceType.Texture: extensions = new[] { "png", "jpg", "gif", "bmp" }; break; case ResourceType.PanoramaLayout: extensions = new[] { "xml", "vxml" }; break; case ResourceType.PanoramaScript: extensions = new[] { "js", "vjs" }; break; case ResourceType.PanoramaStyle: extensions = new[] { "css", "vcss" }; break; case ResourceType.Mesh: extensions = new[] { "obj" }; break; } //Did we find a format we like? if (extensions != null) { var dialog = new SaveFileDialog { FileName = Path.GetFileName(Path.ChangeExtension(fileName, extensions[0])), InitialDirectory = Settings.Config.SaveDirectory, DefaultExt = extensions[0], }; var filter = string.Empty; foreach (var extension in extensions) { filter += $"{extension} files (*.{extension})|*.{extension}|"; } //Remove the last | dialog.Filter = filter.Substring(0, filter.Length - 1); var result = dialog.ShowDialog(); if (result == DialogResult.OK) { Settings.Config.SaveDirectory = Path.GetDirectoryName(dialog.FileName); Settings.Save(); using (var stream = dialog.OpenFile()) { switch (resource.ResourceType) { case ResourceType.Sound: var soundData = ((Sound)resource.Blocks[BlockType.DATA]).GetSound(); stream.Write(soundData, 0, soundData.Length); break; case ResourceType.Texture: var format = SKEncodedImageFormat.Png; switch (dialog.FilterIndex) { case 2: format = SKEncodedImageFormat.Jpeg; break; case 3: format = SKEncodedImageFormat.Gif; break; case 4: format = SKEncodedImageFormat.Bmp; break; } var image = SKImage.FromBitmap(((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap()); using (var data = image.Encode(format, 100)) { data.SaveTo(stream); } break; case ResourceType.PanoramaLayout: case ResourceType.PanoramaScript: case ResourceType.PanoramaStyle: var panoramaData = ((Panorama)resource.Blocks[BlockType.DATA]).Data; stream.Write(panoramaData, 0, panoramaData.Length); break; case ResourceType.Mesh: using (var objStream = new StreamWriter(stream)) using (var mtlStream = new StreamWriter(Path.ChangeExtension(dialog.FileName, "mtl"))) { MeshObject.WriteObject(objStream, mtlStream, Path.GetFileNameWithoutExtension(dialog.FileName), resource); } foreach (var texture in tag.Renderer.MaterialLoader.LoadedTextures) { Console.WriteLine($"Exporting texture for mesh: {texture}"); var textureResource = FileExtensions.LoadFileByAnyMeansNecessary(texture + "_c", tag.Renderer.CurrentFileName, tag.Renderer.CurrentPackage); var textureImage = SKImage.FromBitmap(((Texture)textureResource.Blocks[BlockType.DATA]).GenerateBitmap()); using (var texStream = new FileStream(Path.Combine(Path.GetDirectoryName(dialog.FileName), Path.GetFileNameWithoutExtension(texture) + ".png"), FileMode.Create, FileAccess.Write)) using (var data = textureImage.Encode(SKEncodedImageFormat.Png, 100)) { data.SaveTo(texStream); } } break; } } } } Console.WriteLine($"Export requested for {fileName} Complete"); }
//Експортувати у файл private void ExportButton_OnClick(object sender, RoutedEventArgs e) { ComboBoxItem comboItem = (ComboBoxItem)ComboBox.SelectedItem; //Експортувати в документ PDF if (comboItem.Name != null && comboItem.Name.ToString() == "Pdf") { string extension = "pdf"; // SaveFileDialog dialog = new SaveFileDialog() { DefaultExt = extension, RestoreDirectory = true, Title = "Збереження", Filter = String.Format("Файл {1} (*.{0})|*.{0}|Всі файли (*.*)|*.*", extension, "Pdf"), FilterIndex = 1 }; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { //параметри експорту PositionsGridView.ExportToPdf(stream, new GridViewPdfExportOptions() { ShowColumnHeaders = true, ShowColumnFooters = true, ShowGroupFooters = true, ExportDefaultStyles = true, PageOrientation = PageOrientation.Landscape }); //Повідомлення про успішне експортування MessageBox.Show("Експорт у файл Pdf виконано успішно!", "Повідомлення", MessageBoxButton.OK, MessageBoxImage.Information); } } } //Експортувати в документ Excel if (comboItem.Name != null && comboItem.Name.ToString() == "Xlsx") { string extension = "xlsx"; SaveFileDialog dialog = new SaveFileDialog() { DefaultExt = extension, Title = "Збереження", RestoreDirectory = true, Filter = String.Format("Файл {1} (*.{0})|*.{0}|Всі файли (*.*)|*.*", extension, "Excel"), FilterIndex = 1 }; if (dialog.ShowDialog() == true) { using (Stream stream = dialog.OpenFile()) { //параметри експорту PositionsGridView.ExportToXlsx(stream, new GridViewDocumentExportOptions() { ShowColumnFooters = true, ShowColumnHeaders = true, ShowGroupFooters = true, ExportDefaultStyles = true }); //Повідомлення про успішне експортування MessageBox.Show("Експорт у файл Excel виконано успішно!", "Повідомлення", MessageBoxButton.OK, MessageBoxImage.Information); } } } }
/// <summary> /// 标准导出Excel /// </summary> /// <param name="dgv"></param> /// <param name="pb"></param> /// <returns></returns> public static bool ExportToTxt(DataGridView dgv, ProgressBar pb) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Excel文件(*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存为Excel本文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dgv.ColumnCount; i++) { if (dgv.Columns[i].Visible == true) { if (i > 0) { columnTitle += "\t"; } columnTitle += dgv.Columns[i].HeaderText; } } columnTitle.Remove(columnTitle.Length - 1); sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dgv.Rows.Count; j++) { string columnValue = ""; pb.Value = (j + 1) * 100 / dgv.Rows.Count; for (int k = 0; k < dgv.Columns.Count; k++) { if (dgv.Columns[k].Visible == true) { if (k > 0) { columnValue += "\t"; } if (dgv.Rows[j].Cells[k].Value == null) { columnValue += ""; } else { string m = dgv.Rows[j].Cells[k].Value.ToString().Trim(); columnValue += m.Replace("\t", ""); } } } columnValue.Remove(columnValue.Length - 1); sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); MessageBox.Show("导出完成!"); } catch (Exception e) { MessageBox.Show(e.ToString()); return(false); } finally { sw.Close(); myStream.Close(); } return(true); } else { return(false); } }
private static void OnExecuteExportToExcel(object sender, ExecutedRoutedEventArgs args) { ExcelOptionsConverter excelOptions = new ExcelOptionsConverter(); var treeGrid = args.Source as SfTreeGrid; if (treeGrid == null) { return; } try { ExcelEngine excelEngine = null; var options = args.Parameter as TreeGridExcelExportingOptions; options.ExcelVersion = ExcelVersion.Excel2013; options.ExportingEventHandler = ExportingHandler; if (excelOptions.IsCutomized) { options.CellsExportingEventHandler = CustomizeCellExportingHandler; } else { options.CellsExportingEventHandler = CellExportingHandler; } excelEngine = new ExcelEngine(); IWorkbook workBook = excelEngine.Excel.Workbooks.Create(); treeGrid.ExportToExcel(workBook, options); SaveFileDialog sfd = new SaveFileDialog { FilterIndex = 2, Filter = "Excel 97 to 2003 Files(*.xls)|*.xls|Excel 2007 to 2010 Files(*.xlsx)|*.xlsx", FileName = "Book1" }; if (sfd.ShowDialog() == true) { using (Stream stream = sfd.OpenFile()) { if (sfd.FilterIndex == 1) { workBook.Version = ExcelVersion.Excel97to2003; } else { workBook.Version = ExcelVersion.Excel2010; } workBook.SaveAs(stream); } //Message box confirmation to view the created spreadsheet. if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer] System.Diagnostics.Process.Start(sfd.FileName); } } } catch (Exception) { } }
private void kaedeOutput(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = GlobalData.Instance.data.companyName + ".kae"; sfd.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath); sfd.Filter = "楓ちゃん萌え萌え filez (*.kae)|*.kae"; sfd.RestoreDirectory = true; if (sfd.ShowDialog() != DialogResult.OK) { return; } bool zaikouAsOB = false; if (MessageBox.Show("在校生の氏名データを残しますか?\n" + "はい・・・全員をOBとして扱います\n" + "いいえ・・・在校生は年組番号で出力します", "在校生の扱い", MessageBoxButtons.YesNo) == DialogResult.Yes) { zaikouAsOB = true; } const string kae_header = "Kaede chan moemoe software by 51st. ennichi han"; const int kae_file_version = 1003; const int kae_version = 1005; //kaede_rg005 IItemDao itemDao = GlobalData.getIDao <IItemDao>(); List <Item> items = itemDao.GetAll(); Dictionary <string, int> exSellers = new Dictionary <string, int>(); int exnum = 1; foreach (Item it in items) { if (it.item__Receipt.receipt_seller == Receipt.seller_DONATE || it.item__Receipt.receipt_seller == Receipt.seller_LAGACY) { continue; } if (it.item__Receipt.receipt_seller == Receipt.seller_EXT || zaikouAsOB) { string exname = it.item__Receipt.getSellerString(); if (!exSellers.ContainsKey(exname)) { exSellers.Add(exname, exnum); exnum++; } } } try { using (Stream fs = sfd.OpenFile()) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(Encoding.ASCII.GetBytes(kae_header)); bw.Write(kae_file_version); bw.Write(kae_version); //OB bw.Write(exSellers.Count); foreach (var exs in exSellers) { bw.WriteStringSJIS(exs.Key); } //teacher bw.Write(0); //genre bw.Write(0); //shape bw.Write(0); //item bw.Write(items.Count); foreach (Item it in items) { //ID bw.Write((Int32)it.item_id); //Seller Int32 seller; string sellerstr = it.item__Receipt.receipt_seller; switch (sellerstr) { case Receipt.seller_LAGACY: { seller = 0x30000000; break; } case Receipt.seller_DONATE: { seller = 0x40000000; break; } default: { if (sellerstr == Receipt.seller_EXT || zaikouAsOB) { seller = 0x10000000 + exSellers[it.item__Receipt.getSellerString()]; break; } int nen = int.Parse(sellerstr.Substring(0, 1)); string kumi = sellerstr.Substring(1, 1); int kumi_i; if (Globals.isChugaku(kumi)) { kumi_i = Globals.getChugakuClassNum(kumi); } else { nen += 3; kumi_i = int.Parse(kumi); } int ban = int.Parse(sellerstr.Substring(2, 2)); seller = 0x01000000 * nen + 0x00100000 * kumi_i + ban; break; } } bw.Write(seller); bw.WriteStringSJIS(it.item_name); bw.WriteStringSJIS(it.item_comment); bw.Write(it.item_tagprice); bw.Write(it.item_sellprice.ToKaedeInt()); //Genre bw.Write((Int16)0); bw.Write((Int16)0); bw.Write((Int16)0); //Shape bw.Write((Int16)0); //is_sold bw.Write(it.item_sellprice.HasValue.ToKaedeBool()); //is_returned bw.Write((SByte)0); //to_be_return bw.Write(it.item_return.ToKaedeBool()); //to_be_discount bw.Write(it.item_tataki.ToKaedeBool()); if (it.item_receipt_time.HasValue) { bw.Write(it.item_receipt_time.Value.ToUnixTime()); } else if (it.item__Receipt.receipt_time.HasValue) { bw.Write(it.item__Receipt.receipt_time.Value.ToUnixTime()); } else { bw.Write((UInt32)0); } if (it.item_selltime.HasValue) { bw.Write(it.item_selltime.Value.ToUnixTime()); } else { bw.Write((UInt32)0); } //Item_scheduled_date bw.Write((SByte)0); //is_by_auction bw.Write((SByte)0); //refund_rate bw.Write((Int32)(-1)); } //cash bw.Write((Int32)888); //refund_rate bw.Write((Int32)100); bw.Flush(); fs.Close(); } uint[] crcTable = new uint[256]; for (uint n = 0; n < 256; n++) { uint c = n; for (uint k = 0; k < 8; k++) { if ((c & 1) != 0) { c = 0xedb88320U ^ (c >> 1); } else { c = c >> 1; } } crcTable[n] = c; } using (FileStream fs = new FileStream(sfd.FileName, FileMode.Open, FileAccess.ReadWrite)) { uint not_crc = 0xffffffff; BinaryReader br = new BinaryReader(fs); while (fs.Position < fs.Length) { byte data = br.ReadByte(); not_crc = crcTable[((not_crc) ^ (data)) & 0xff] ^ ((not_crc) >> 8); } BinaryWriter bw = new BinaryWriter(fs); bw.Write(~not_crc); bw.Flush(); fs.Close(); } } catch (Exception ex) { MessageBox.Show("kaeファイルの作成エラー: " + ex.Message); return; } MessageBox.Show("楓ちゃん形式での出力が完了しました。"); }
/// <summary> /// 将DataTable中数据写入到CSV文件中 /// </summary> /// <param name="dt">提供保存数据的DataTable</param> /// <param name="fileName">CSV的文件路径</param> public static void SaveCSV(DataTable dt, string fileName) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Csv文件(*.csv)|*.csv"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Csv文件到"; saveFileDialog.FileName = fileName; DialogResult result = saveFileDialog.ShowDialog(); if (result == DialogResult.Cancel) { Program.logger.LogInfo("文件\"{0}\"取消保存", fileName); return; } Stream myStream; myStream = saveFileDialog.OpenFile(); //FileInfo fi = new FileInfo(fullPath); //if (!fi.Directory.Exists) //{ // fi.Directory.Create(); //} //FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.UTF8); string data = ""; try { DataView dataView = dt.DefaultView; dataView.Sort = string.Format("{0} asc,{1} asc", CommonUtils.heads[0], CommonUtils.heads[1]); dt = dataView.ToTable(); //dt.DefaultView.Sort = string.Format("{0} asc,{1} asc", CommonUtils.heads[0], CommonUtils.heads[1]); //写出列名称 for (int i = 0; i < dt.Columns.Count; i++) { data += dt.Columns[i].ColumnName.ToString(); if (i < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); //写出各行数据 for (int i = 0; i < dt.Rows.Count; i++) { data = ""; for (int j = 0; j < dt.Columns.Count; j++) { string str = dt.Rows[i][j].ToString(); str = str.Replace("\"", "\"\""); //替换英文冒号 英文冒号需要换成两个冒号 if (str.Contains(',') || str.Contains('"') || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中 { str = string.Format("\"{0}\"", str); } data += str; if (j < dt.Columns.Count - 1) { data += ","; } } sw.WriteLine(data); } sw.Close(); myStream.Close(); Program.logger.LogInfo("文件\"{0}\"保存成功", fileName); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); } //fs.Close(); //DialogResult result = MessageBox.Show("CSV文件保存成功!"); //if (result == DialogResult.OK) //{ // //System.Diagnostics.Process.Start("explorer.exe", Common.PATH_LANG); //} }