Example #1
0
        void InitializeExportButton()
        {
            DXPopupMenu popup = new DXPopupMenu();

            DXMenuItem item = new DXMenuItem(ExportFormat.Image.ToString(), exportPopupItem_Click);

            exportHashtable.Add(item, ExportFormat.Image);
            popup.Items.Add(item);

            item = new DXMenuItem(ExportFormat.Mht.ToString(), exportPopupItem_Click);
            exportHashtable.Add(item, ExportFormat.Mht);
            popup.Items.Add(item);

            item = new DXMenuItem(ExportFormat.Pdf.ToString(), exportPopupItem_Click);
            exportHashtable.Add(item, ExportFormat.Pdf);
            popup.Items.Add(item);

            item = new DXMenuItem(ExportFormat.Xls.ToString(), exportPopupItem_Click);
            exportHashtable.Add(item, ExportFormat.Xls);
            popup.Items.Add(item);

            item = new DXMenuItem(ExportFormat.Xlsx.ToString(), exportPopupItem_Click);
            exportHashtable.Add(item, ExportFormat.Xlsx);
            popup.Items.Add(item);

            ddbExport.DropDownControl = popup;
            ddbExport.Text            = exportButtonTextBase + exportFormat.ToString();
        }
Example #2
0
        /// <summary>
        /// 导出SmartGridView的数据源的数据
        /// </summary>
        /// <param name="ds">数据源</param>
        /// <param name="headers">导出的表头数组</param>
        /// <param name="fields">导出的字段数组</param>
        /// <param name="exportFormat">导出文件的格式</param>
        /// <param name="fileName">输出文件名</param>
        /// <param name="encoding">编码</param>
        private static void Export(DataSet ds, string[] headers, string[] fields, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer      = true;
            HttpContext.Current.Response.ContentType = String.Format("text/{0}", exportFormat.ToString().ToLower());
            HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.{1}", fileName, exportFormat.ToString().ToLower()));
            HttpContext.Current.Response.ContentEncoding = encoding;

            MemoryStream  stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, encoding);

            CreateStylesheet(writer, headers, fields, exportFormat);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);

            XmlDataDocument      xmlDoc  = new XmlDataDocument(ds);
            XslCompiledTransform xslTran = new XslCompiledTransform();

            xslTran.Load(new XmlTextReader(stream));

            System.IO.StringWriter sw = new System.IO.StringWriter();
            xslTran.Transform(xmlDoc, null, sw);

            HttpContext.Current.Response.Write(sw.ToString());
            sw.Close();
            writer.Close();
            stream.Close();
            HttpContext.Current.Response.End();
        }
        private static TagBuilder CreateToolbarLink(ExportFormat exportFormat, string href)
        {
            TagBuilder link = new TagBuilder("a");

            link.Attributes.AddRange(new[]
            {
                new KeyValuePair <string, string>("class", "k-button k-button-icontext"),
                new KeyValuePair <string, string>("style", "float: right;"),
                new KeyValuePair <string, string>("href", href)
            });

            TagBuilder span = new TagBuilder("span");

            switch (exportFormat)
            {
            case ExportFormat.Excel:
                span.AddCssClass("k-icon k-i-file-excel");

                break;

            case ExportFormat.Pdf:
                link.AddCssClass("k-grid-pdf");
                span.AddCssClass("k-icon k-i-file-pdf");
                break;

            default:
                throw new Exception("Type de ExportFormat non supporté.");
            }

            link.InnerHtml.AppendHtml(span);

            link.InnerHtml.Append(exportFormat.ToString());

            return(link);
        }
Example #4
0
        private Button CreateButton(ExportFormat format)
        {
            var btn = new NoFocusButton();

            btn.BackColor  = BackColor;
            btn.ForeColor  = Direct2DGraphics.ToDrawingColor4(Theme.LightGreyFillColor2);
            btn.ImageAlign = ContentAlignment.MiddleLeft;
            btn.TextAlign  = ContentAlignment.MiddleLeft;
            btn.FlatStyle  = FlatStyle.Flat;
            btn.FlatAppearance.BorderSize         = 0;
            btn.FlatAppearance.MouseOverBackColor = Direct2DGraphics.ToDrawingColor4(Theme.DarkGreyFillColor2);
            btn.FlatAppearance.MouseDownBackColor = Direct2DGraphics.ToDrawingColor4(Theme.DarkGreyFillColor2);
            btn.Image             = (Bitmap)Resources.ResourceManager.GetObject("Export" + format.ToString(), Resources.Culture);
            btn.Top               = ((int)format) * 32;
            btn.Left              = 0;
            btn.Width             = panelTabs.Width;
            btn.Height            = 32;
            btn.Font              = format == 0 ? fontBold : font;
            btn.Text              = format.ToString();
            btn.TextImageRelation = TextImageRelation.ImageBeforeText;
            btn.Click            += Btn_Click;

            panelTabs.Controls.Add(btn);

            return(btn);
        }
Example #5
0
        public static byte[] Render(string ssrUrl, ExportFormat exportFormat, Dictionary <string, string> parametersAndValues, string reportName, ICredentials credentials)
        {
            using (var reportExecution = new ReportExecutionService(ssrUrl)
            {
                Credentials = credentials ?? CredentialCache.DefaultCredentials
            })
            {
                string    encoding;
                string    mimeType;
                string    extension;
                Warning[] warnings;
                string[]  streamIDs;

                reportExecution.LoadReport(reportName, null);
                if (parametersAndValues.Count > 0)
                {
                    var parameters = new ParameterValue[parametersAndValues.Count];
                    var i          = 0;
                    foreach (var paramsAndValues in parametersAndValues)
                    {
                        parameters[i] = new ParameterValue
                        {
                            Name = paramsAndValues.Key, Value = paramsAndValues.Value
                        };
                        i++;
                    }
                    reportExecution.SetExecutionParameters(parameters, "en-us");
                }
                var results = reportExecution.Render(exportFormat.ToString(), null, out extension, out mimeType,
                                                     out encoding, out warnings, out streamIDs);
                return(results);
            }
        }
Example #6
0
        private static List <string> EnumerateFiles(string path, ExportFormat format)
        {
            if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                path += Path.DirectorySeparatorChar;
            }

            return(Directory.EnumerateFiles(path, $"*.{format.ToString().ToLower()}", SearchOption.AllDirectories).ToList());
        }
Example #7
0
 /// <summary>
 /// 获取文件名
 /// </summary>
 private string GetFileName(string fileName)
 {
     if (fileName.IsEmpty())
     {
         fileName = Table.Title;
     }
     if (fileName.IsEmpty())
     {
         fileName = DateTime.Now.ToDateString();
     }
     return(fileName + "." + _format.ToString().ToLower());
 }
Example #8
0
        internal void Save(XElement xParent)
        {
            var nfi = new NumberFormatInfo();

            nfi.NumberDecimalSeparator = ".";

            xParent.Add(
                new XElement("Drawing",
                             new XAttribute("Name", DrawingName),
                             new XElement("ExportFormat", ExportFormat.ToString()),
                             new XElement("DrawingSize", DrawingSize.ToString(nfi)),
                             new XElement("SaveDrawingSize", SaveDrawingSize.ToString())));
        }
Example #9
0
        public static ImageExportFormat ExportFormatToImageExportFormat(ExportFormat format)
        {
            Debug.Assert(!EnumHelper.HasDuplicateValues <ExportFormat>());

            switch (format)
            {
            case ExportFormat.Invalid:
            case ExportFormat.Pdf:
                throw new NotImplementedException(format.ToString());

            default:
                return((ImageExportFormat)(int)format);
            }
        }
Example #10
0
 /// <summary>
 /// Streams the memory stream back to the client.
 /// </summary>
 /// <remarks>The exported image is written to the output stream of the response object.</remarks>
 /// <param name="ms">Memory stream containing the exported image.</param>
 public virtual void StreamImageToClient(MemoryStream ms)
 {
     if (ms != null)
     {
         string       contentType = string.Format("image/{0}", ExportFormat.ToString());
         BinaryReader reader      = new BinaryReader(ms);
         int          length      = (int)ms.Length;
         if (contentType != null)
         {
             HttpContext.Current.Response.ContentType = contentType;
         }
         HttpContext.Current.Response.OutputStream.Write(reader.ReadBytes(length), 0, length);
         reader.Close();
         ms.Close();
     }
 }
Example #11
0
 private void SaveToFile(string data)
 {
     try {
         var extension      = format.ToString();
         var saveFileDialog = new SaveFileDialog {
             DefaultExt = "." + extension.ToLower(),
             Filter     = extension + @" format|." + extension.ToLower()
         };
         if (saveFileDialog.ShowDialog() != DialogResult.OK)
         {
             return;
         }
         File.WriteAllText(saveFileDialog.FileName, data);
         Dialogs.Info("Export written to:\n " + saveFileDialog.FileName);
     }
     catch (Exception e) {
         throw new Exception(e.Message);
     }
 }
        private string GetFullFilePath(int diagramIndex = 0, bool overwriteFiles = true)
        {
            string outputPath     = OutputPath;
            string filenameFormat = SelectedFilenameFormat;

            string filePath = "";

            for (int i = 0; i < SelectedFilenameFormat.Length; i++)
            {
                if (SelectedFilenameFormat[i] != '%')
                {
                    filePath += SelectedFilenameFormat[i];
                }
                else
                {
                    if (i + 1 < SelectedFilenameFormat.Length)
                    {
                        i++; // step forward to look at the next character
                        char nextChar = SelectedFilenameFormat[i];
                        switch (nextChar)
                        {
                        case 't':
                            filePath += CleanTitle(DiagramsToExport[diagramIndex].Title);
                            break;

                        case 'c':
                            filePath += CollectionName;
                            break;

                        case 'h':
                            filePath += DiagramsToExport[diagramIndex].TotalHeight.ToString();
                            break;

                        case 'w':
                            filePath += DiagramsToExport[diagramIndex].TotalWidth.ToString();
                            break;

                        case '0':
                            filePath += diagramIndex.ToString();
                            break;

                        case '1':
                            filePath += (diagramIndex + 1).ToString();
                            break;

                        case '#':
                            filePath += DiagramsToExport.Count.ToString();
                            break;

                        case 'x':
                            filePath += ExportFormat.ToString().ToLower();
                            break;

                        case 'X':
                            filePath += ExportFormat.ToString().ToUpper();
                            break;

                        case '%':
                            filePath += "%";
                            break;

                        default:
                            //i--; // back up so we don't miss the next character
                            break;
                        }
                    }
                }
            }

            string rawFileName = FolderUtils.CleanPath(Path.Combine(outputPath, filePath));

            string folder    = Path.GetDirectoryName(rawFileName);
            string fileName  = Path.GetFileNameWithoutExtension(rawFileName);
            string extension = Path.GetExtension(rawFileName);

            string testfileName = Path.Combine(folder, fileName + extension);

            int  attempt       = 1;
            bool foundFilename = false;

            while (!foundFilename)
            {
                bool fileAlreadyExists     = File.Exists(testfileName);
                bool fileCreatedThisExport = _createdFiles.Exists(createdFile => createdFile.Equals(testfileName, StringComparison.CurrentCultureIgnoreCase));

                if (!fileAlreadyExists || (fileAlreadyExists && !fileCreatedThisExport && overwriteFiles))
                {
                    foundFilename = true;
                }
                else
                {
                    testfileName = Path.Combine(folder, fileName + " (" + attempt + ")" + extension);
                    attempt++;
                }
            }

            return(testfileName);
        }
Example #13
0
    /// <summary>
    /// Web Utility Function For Exporting Data Set to Specified Format
    /// </summary>
    /// <param name="dsResults">Result Data Set</param>
    /// <param name="enExport">Export Enum Values</param>
    /// <param name="strColDelim">Column Delimiter value</param>
    /// <param name="strRowDelim"></param>
    /// <param name="strFileName"></param>
    public static void ExportDataSet(DataSet dsResults, ExportFormat enExport, string strColDelim, string strRowDelim, string strFileName)
    {
        DataGrid dgExport = new DataGrid();

        dgExport.AllowPaging  = false;
        dgExport.DataSource   = dsResults;
        dsResults.DataSetName = "WebERP";
        dgExport.DataMember   = dsResults.Tables[0].TableName;
        dgExport.DataBind();
        System.Web.HttpContext.Current.Response.Clear();
        System.Web.HttpContext.Current.Response.Buffer          = true;
        System.Web.HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
        System.Web.HttpContext.Current.Response.Charset         = "";
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        switch (enExport.ToString().ToLower())
        {
        case "xls":
        {
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            dgExport.RenderControl(oHtmlTextWriter);
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString());
            break;
        }

        case "custom":
        {
            string strText;
            System.Web.HttpContext.Current.Response.ContentType = "text/txt";
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            dgExport.RenderControl(oHtmlTextWriter);
            strText = oStringWriter.ToString();
            strText = ParseToDelim(strText, strRowDelim, strColDelim);
            System.Web.HttpContext.Current.Response.Write(strText);
            break;
        }

        case "csv":
        {
            string strText;
            strRowDelim = System.Environment.NewLine;
            strColDelim = ",";
            System.Web.HttpContext.Current.Response.ContentType = "text/txt";
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            dgExport.RenderControl(oHtmlTextWriter);
            strText = oStringWriter.ToString();
            strText = ParseToDelim(strText, strRowDelim, strColDelim);
            System.Web.HttpContext.Current.Response.Write(strText);
            break;
        }

        case "tsv":                 //tab seperated
        {
            string strText;
            strRowDelim = System.Environment.NewLine;
            strColDelim = "\t";
            System.Web.HttpContext.Current.Response.ContentType = "text/txt";
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            dgExport.RenderControl(oHtmlTextWriter);
            strText = oStringWriter.ToString();
            strText = ParseToDelim(strText, strRowDelim, strColDelim);
            System.Web.HttpContext.Current.Response.Write(strText);
            break;
        }

        case "xml":
        {
            System.Web.HttpContext.Current.Response.ContentType = "text/xml";
            System.Web.HttpContext.Current.Response.Write(dsResults.GetXml());
            break;
        }

        case "htm":
        {
            System.Web.HttpContext.Current.Response.ContentType = "text/html";
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            dgExport.RenderControl(oHtmlTextWriter);
            System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString());
            break;
        }
        }


        System.Web.HttpContext.Current.Response.End();
    }
        public async Task Import(string path, ExportFormat format, Language?language, byte[] content, bool overwrite)
        {
            var request = new { path, format = format.ToString(), language = language?.ToString(), content, overwrite };

            await HttpPost <dynamic>(this.HttpClient, "workspace/import", request).ConfigureAwait(false);
        }
Example #15
0
        private void OnInitialiseMapManagerCompleted(object sender, InitialiseMapManagerEventArgs e)
        {
            if (e.IsInitialised)
            {
                ProgressRecord progressRecord = new ProgressRecord(0, "Exporting Glyma Map", string.Format("Initialising {0} export processor", ExportFormat.ToString()));
                progressRecord.SecondsRemaining = -1;
                progressRecord.PercentComplete  = 5;
                progressRecord.RecordType       = ProgressRecordType.Processing;

                lock (pr_lock)
                {
                    this.ProgressRecord = progressRecord;
                    ProgressEvent.Set(); //notify of change to progress
                }

                ExportUtilityFactory exportFactory = new ExportUtilityFactory(MapManager);
                IExportUtility       exportUtil    = null;
                switch (MapSchema)
                {
                case "IBIS":
                    switch (ExportFormat)
                    {
                    case "Compendium":
                        exportUtil = exportFactory.CreateExportUtility(MapType.IBIS, ExportType.Compendium);
                        break;

                    case "Word":
                        exportUtil = exportFactory.CreateExportUtility(MapType.IBIS, ExportType.Word);
                        break;

                    case "PDF":
                        exportUtil = exportFactory.CreateExportUtility(MapType.IBIS, ExportType.PDF);
                        break;

                    case "GlymaXML":
                        //exportUtil = exportFactory.CreateExportUtility(MapType.IBIS, ExportType.GlymaXml);
                        lock (msg_lock)
                        {
                            Message = "Exporting to GlymaXML format is currently not supported";
                            LogMessageEvent.Set();
                        }
                        break;
                    }
                    break;
                }
                exportUtil.ExportCompleted += OnExportCompleted;
                exportUtil.ProgressChanged += OnProgressChanged;


                ExportPropertiesDictionary exportProps = CreateExportProperties();
                GlymaExportUserState       userState   = new GlymaExportUserState(Output);

                progressRecord = new ProgressRecord(0, "Exporting Glyma Map", "Export Progress: 0%");
                progressRecord.SecondsRemaining = -1;
                progressRecord.PercentComplete  = 10;
                progressRecord.RecordType       = ProgressRecordType.Processing;

                lock (pr_lock)
                {
                    this.ProgressRecord = progressRecord;
                    ProgressEvent.Set(); //notify of change to progress
                }

                exportUtil.ExportMap(Domain, Map, exportProps, null, userState);
                bool signalled = userState.Completed.WaitOne(Timeout.Infinite); //wait for the export to completed
                if (!signalled)
                {
                    Completed.Set(); //since it's inifinite timeout this shouldn't happen
                }
            }
            else
            {
                lock (msg_lock)
                {
                    this.Message = string.Format("Failed to initialise the web service client: {0}", e.ErrorMessage);
                    LogMessageEvent.Set();
                }

                Completed.Set();
            }
        }
Example #16
0
        public string ExportDetails(DataSet dataset, ExportFormat formatType, string filename)
        {
            if (dataset.Tables.Count < 2 && formatType == ExportFormat.CSV)
            {
                using (var writer = File.CreateText(filename))
                {
                    WriteCSV(dataset.Tables[0], writer);
                    writer.Flush();
                }
                return(filename);
            }

            if (formatType == ExportFormat.CSV)
            {
                //need to write each query result to a separate file and zip up
                if (System.IO.Path.GetExtension(filename) != "zip")
                {
                    filename = Path.ChangeExtension(filename, "zip");
                }

                using (var filestream = new FileStream(filename, FileMode.Create))
                    using (var zipstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(filestream))
                    {
                        for (int i = 0; i < dataset.Tables.Count; i++)
                        {
                            var table = dataset.Tables[i];

                            string zipEntryFilename = Path.ChangeExtension(table.TableName, "csv");

                            var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename);
                            zipEntry.DateTime = DateTime.Now;
                            zipstream.PutNextEntry(zipEntry);

                            using (var writer = new StreamWriter(zipstream, Encoding.Default, 1024, true))
                            {
                                WriteCSV(table, writer);
                                writer.Flush();
                            }
                        }
                    }

                return(filename);
            }
            else if (formatType == ExportFormat.Excel)
            {
                //need to write each query result to a separate tab, with the tab name the queryname
                using (var filestream = File.Create(filename, 1024))
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Create(filestream, SpreadsheetDocumentType.Workbook))
                    {
                        WorkbookPart workbookPart = doc.AddWorkbookPart();
                        workbookPart.Workbook            = new Workbook();
                        doc.WorkbookPart.Workbook.Sheets = new Sheets();
                        Sheets sheets = doc.WorkbookPart.Workbook.GetFirstChild <Sheets>();

                        var excelValidator = new Lpp.Utilities.Excel.ExcelEx();

                        for (uint sheetID = 1; sheetID <= dataset.Tables.Count; sheetID++)
                        {
                            var table = dataset.Tables[((int)sheetID) - 1];

                            WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
                            Sheet         sheet         = new Sheet {
                                Id = doc.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = sheetID, Name = excelValidator.ValidateTabName(table.TableName)
                            };
                            sheets.Append(sheet);

                            SheetData sheetData = new SheetData();
                            worksheetPart.Worksheet = new Worksheet(sheetData);

                            Row headerRow = new Row();
                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                headerRow.AppendChild(new Cell {
                                    DataType = CellValues.String, CellValue = new CellValue(table.Columns[i].ColumnName)
                                });
                            }
                            sheetData.AppendChild(headerRow);

                            Row dataRow;
                            for (int j = 0; j < table.Rows.Count; j++)
                            {
                                dataRow = new Row();
                                var row = table.Rows[j];
                                for (int k = 0; k < row.ItemArray.Length; k++)
                                {
                                    dataRow.AppendChild(new Cell {
                                        DataType = CellValues.String, CellValue = new CellValue(row.ItemArray[k].ToStringEx())
                                    });
                                }
                                sheetData.AppendChild(dataRow);
                            }

                            worksheetPart.Worksheet.Save();
                        }
                    }

                return(filename);
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(formatType), "formatType", "Invalid export format type value: " + formatType.ToString());
            }
        }
Example #17
0
        private static void Export(this DataSet ds, string[] headers, string[] fields, ExportFormat exportFormat, string fileName, Encoding encoding)
        {
            SysVariable.CurrentContext.Response.Clear();
            SysVariable.CurrentContext.Response.Buffer      = true;
            SysVariable.CurrentContext.Response.ContentType = string.Format("text/{0}", exportFormat.ToString().ToLower());
            SysVariable.CurrentContext.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.{1}", fileName, exportFormat.ToString().ToLower()));
            SysVariable.CurrentContext.Response.ContentEncoding = encoding;
            MemoryStream  w      = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(w, encoding);

            CreateStylesheet(writer, headers, fields, exportFormat);
            writer.Flush();
            w.Seek(0L, SeekOrigin.Begin);
            XmlDataDocument      document  = new XmlDataDocument(ds);
            XslCompiledTransform transform = new XslCompiledTransform();

            transform.Load(new XmlTextReader(w));
            StringWriter writer2 = new StringWriter();

            transform.Transform((IXPathNavigable)document, null, (TextWriter)writer2);
            SysVariable.CurrentContext.Response.Write(writer2.ToString());
            writer2.Close();
            writer.Close();
            w.Close();
            SysVariable.CurrentContext.Response.End();
        }
Example #18
0
        private static void SaveOutput(Type listElementType, ExportFormat format, XmlNode rawData, FileInfo outputFile)
        {
            switch (format)
            {
            case ExportFormat.Xml:
                XDocument.Parse(rawData.OuterXml).Save(outputFile.FullName);
                break;

            case ExportFormat.Csv:
                var document = XDocument.Parse(rawData.OuterXml);

                var  mainElement = document.Elements().FirstOrDefault();
                bool firstLine   = true;

                using (TextWriter writer = new StreamWriter(outputFile.FullName, false, Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage)))
                {
                    if (mainElement != null)
                    {
                        // Find the properties that aren't ignored
                        var headers = listElementType.GetProperties().Where(p => !p.CustomAttributes.Any(a => a.AttributeType.Name.Contains("Ignore"))).ToList();

                        // Print them to the file as CSV headers
                        writer.WriteLine(string.Join(
                                             System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator,
                                             headers.Select(a => string.Format("\"{0}\"", a.Name))));

                        // Loop each XML element
                        foreach (XElement childElement in mainElement.Elements())
                        {
                            // Loop through each property in the header reference list
                            var cells = new List <string>();
                            foreach (var propertyInfo in headers)
                            {
                                var elementvalue   = childElement.Elements().FirstOrDefault(e => e.Name.LocalName.ToLower() == propertyInfo.Name.ToLower());
                                var attributevalue = childElement.Attributes().FirstOrDefault(e => e.Name.LocalName.ToLower() == propertyInfo.Name.ToLower());

                                // Did any element or attribute fit?
                                if (elementvalue != null)
                                {
                                    cells.Add(elementvalue.Value);
                                }
                                else if (attributevalue != null)
                                {
                                    cells.Add(attributevalue.Value);
                                }
                                else
                                {
                                    // Empty is also fine
                                    cells.Add(string.Empty);
                                }
                            }

                            writer.WriteLine(string.Join(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator, cells.Select(a => string.Format("\"{0}\"", a))));
                        }
                    }
                }

                break;

            default:
                throw new ArgumentOutOfRangeException(format.ToString(), format, null);
            }

            Console.WriteLine(string.Empty);
            Console.WriteLine("Output saved to " + outputFile.FullName);
        }
Example #19
0
        /// <summary>
        /// 导出SmartGridView的数据源的数据
        /// </summary>
        /// <param name="ds">数据源</param>
        /// <param name="headers">导出的表头数组</param>
        /// <param name="fields">导出的字段数组</param>
        /// <param name="exportFormat">导出文件的格式</param>
        /// <param name="fileName">输出文件名</param>
        /// <param name="encoding">编码</param>
        /// <param name="function">字段名称 / 函数 对</param>
        private static void Export(DataSet ds, string[] headers, string[] fields,
            ExportFormat exportFormat, string fileName, Encoding encoding, Dictionary<string, string> function)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = String.Format("text/{0}", exportFormat.ToString().ToLower());
            HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.{1}", fileName, exportFormat.ToString().ToLower()));
            HttpContext.Current.Response.ContentEncoding = encoding;

            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, encoding);

            CreateStylesheet(writer, headers, fields, exportFormat, function);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);

            XmlDataDocument xmlDoc = new XmlDataDocument(ds);
            XslCompiledTransform xslTran = new XslCompiledTransform();
            xslTran.Load(new XmlTextReader(stream));

            System.IO.StringWriter sw = new System.IO.StringWriter();
            xslTran.Transform(xmlDoc, null, sw);

            HttpContext.Current.Response.Write(sw.ToString());
            sw.Close();
            writer.Close();
            stream.Close();
            HttpContext.Current.Response.End();
        }