• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# CsvWriter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中CsvWriter的典型用法代码示例。如果您正苦于以下问题:C# CsvWriter类的具体用法?C# CsvWriter怎么用?C# CsvWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CsvWriter类属于命名空间,在下文中一共展示了CsvWriter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: WriteComponentToTheFile

        private void WriteComponentToTheFile(CsvWriter writer, DataTemplateComposite outputDataTemplateComposite)
        {
            foreach (var component in outputDataTemplateComposite.Cast<DataTemplateComponent>())
            {
                if (component.GetType() == typeof(DataTemplateComposite))
                {
                    writer.WriteField(""); writer.WriteField("");
                    writer.WriteField("Name"); writer.WriteField(component.Name);
                    writer.WriteField(""); writer.WriteField("");
                    writer.WriteField(""); writer.WriteField("");
                    writer.NextRecord();
                    WriteComponentToTheFile(writer, component as DataTemplateComposite);
                }
                else
                {
                    if (component.Component == null)
                    {
                        writer.WriteField("Position"); writer.WriteField("n/a");
                        writer.WriteField("Name"); writer.WriteField(component.Name);
                        writer.WriteField("Type"); writer.WriteField("n/a");
                        writer.WriteField("Value"); writer.WriteField("n/a");
                        writer.NextRecord();
                        break;
                    }

                    writer.WriteField("Position"); writer.WriteField(component.Component.Pos);
                    writer.WriteField("Name"); writer.WriteField(component.Component.Name);
                    writer.WriteField("Type"); writer.WriteField(component.Component.TypeOfVariable.ToString());
                    writer.WriteField("Value"); writer.WriteField(component.Component.StringValue().Trim());
                    writer.NextRecord();
                }
            }
        }
开发者ID:KH8,项目名称:PlcAgent,代码行数:33,代码来源:FileCreator.cs


示例2: ExportProductsTest

        public void ExportProductsTest()
        {
            var searchService = GetSearchService();
            var categoryService = GetCategoryService();
            var itemService = GetItemService();
            var result = searchService.Search(new SearchCriteria { CatalogId = "Sony", CategoryId = "66b58f4c-fd62-4c17-ab3b-2fb22e82704a", Skip = 0, Take = 10, ResponseGroup = coreModel.SearchResponseGroup.WithProducts });
            var importConfiguration = GetMapConfiguration();

            using (var csvWriter = new CsvWriter(new StreamWriter(@"c:\Projects\VCF\vc-community\PLATFORM\Modules\Catalog\VirtoCommerce.CatalogModule.Test\products.csv")))
            {
                var csvProducts = new List<CsvProduct>();
                foreach (var product in result.Products)
                {
                    var fullLoadedProduct = itemService.GetById(product.Id, ItemResponseGroup.ItemLarge);
                    csvProducts.Add(new CsvProduct(fullLoadedProduct, null, null, null));
                }

                importConfiguration.PropertyCsvColumns = csvProducts.SelectMany(x => x.PropertyValues).Select(x => x.PropertyName).Distinct().ToArray();
                csvWriter.Configuration.Delimiter = ";";
                csvWriter.Configuration.RegisterClassMap(new CsvProductMap(importConfiguration));

                csvWriter.WriteHeader<CsvProduct>();
                foreach (var product in csvProducts)
                {
                    csvWriter.WriteRecord(product);
                }

            }
        }
开发者ID:adwardliu,项目名称:vc-community,代码行数:29,代码来源:ImportExportTest.cs


示例3: TranslationsCsv

        public FileStreamResult TranslationsCsv(bool admin = false)
        {
            var ms = new MemoryStream();
            var sw = new StreamWriter(ms);
            var csv = new CsvWriter(sw);

            var translations = (from t in db.Translations
                where t.Area == (admin ? TranslationArea.Backend : TranslationArea.Frontend)
                select new
                       {
                           t.LanguageCode,
                           t.Key,
                           t.Value
                       }).ToList();

            csv.WriteHeader(translations.First().GetType());
            foreach (var trans in translations)
            {
                csv.WriteRecord(trans);
            }

            sw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            var result = new FileStreamResult(ms, "application/octet-stream");
            result.FileDownloadName = "Translations_" + DateTime.Now.ToString("yyyyMMddTHHmmss") + ".csv";
            return result;
        }
开发者ID:alin-rautoiu,项目名称:Cart42,代码行数:27,代码来源:DataExportController.cs


示例4: Main

        private static void Main()
        {
            using (var csv = new CsvWriter(new StreamWriter("results.csv", false, Encoding.UTF8)))
            {
                WriteHeader(csv);

                var languagesToTest = new[] {Languages.EnglishUK, Languages.GermanGermany};
                foreach (var language in languagesToTest)
                {
                    var results = new AutoCorrectTester(language).Run();

                    foreach (var result in results)
                    {
                        foreach (var testResult in result.Results)
                        {
                            csv.WriteField(language);
                            csv.WriteField(result.AutoCompleteMethod);
                            csv.WriteField(result.MemorySize);
                            csv.WriteField(testResult.Misspelling);
                            csv.WriteField(testResult.TargetWord);
                            csv.WriteField(testResult.CharactersTyped);
                            csv.WriteField(testResult.TargetWord.Length);
                            csv.WriteField(testResult.TimeTaken.Milliseconds);
                            csv.WriteField(testResult.CharactersTyped != -1
                                ? (double) testResult.CharactersTyped/testResult.TargetWord.Length
                                : 2d);
                            csv.NextRecord();
                        }
                    }
                }
            }
        }
开发者ID:EddPorter,项目名称:OptiKey,代码行数:32,代码来源:Program.cs


示例5: encoding_gets_encoding

 public void encoding_gets_encoding()
 {
     using (var writer = new CsvWriter(new MemoryStream(), Encoding.ASCII))
     {
         Assert.Same(Encoding.ASCII, writer.Encoding);
     }
 }
开发者ID:modulexcite,项目名称:KBCsv,代码行数:7,代码来源:CsvWriterFixture.cs


示例6: record_number_is_zero_by_default

 public void record_number_is_zero_by_default()
 {
     using (var writer = new CsvWriter(new MemoryStream()))
     {
         Assert.Equal(0, writer.RecordNumber);
     }
 }
开发者ID:modulexcite,项目名称:KBCsv,代码行数:7,代码来源:CsvWriterFixture.cs


示例7: CompareChangingValues

        public void CompareChangingValues()
        {
            UserAssist assist = new UserAssist();
            using(CsvWriter writer = new CsvWriter(new StreamWriter(File.Open("ChangingValues.csv", FileMode.Create))))
            {
                writer.WriteHeader<ValueLetter>();
                var snap1Values =
                    assist.Snapshot("snap1.csv")
                    .FindProgram("cmd.exe")
                    .GetValue();

                WaitOpenThenKill("cmd.exe");

                var snap2Values = assist.Snapshot("snap2.csv")
                                        .FindProgram("cmd.exe")
                                        .GetValue();
                for(int i = 0 ; i < snap1Values.Length ; i++)
                {
                    writer.WriteRecord(new ValueLetter()
                    {
                        Position = i,
                        Value1 = snap1Values[i].ToString("X2"),
                        Value2 = snap2Values[i].ToString("X2"),
                        IsDiff = (snap1Values[i] != snap2Values[i]) ? "x" : ""
                    });
                }
            }
            Process.Start("ChangingValues.csv");
        }
开发者ID:NicolasDorier,项目名称:userassist,代码行数:29,代码来源:UnitTest1.cs


示例8: GeneratePerformaceReport

        static void GeneratePerformaceReport()
        {
            var iterations = 50;


            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            using (var csv = new CsvWriter(writer))
            {
                csv.WriteHeader(typeof(PerformaceTestResult));

              /*  csv.WriteRecords(DoTestsForSettings(iterations, false, false, false));
                csv.WriteRecords(DoTestsForSettings(iterations, false, false, true));
                csv.WriteRecords(DoTestsForSettings(iterations, false, true, false));
                csv.WriteRecords(DoTestsForSettings(iterations, false, true, true));


                csv.WriteRecords(DoTestsForSettings(iterations, true, false, false));
                csv.WriteRecords(DoTestsForSettings(iterations, true, false, true));

                csv.WriteRecords(DoTestsForSettings(iterations, true, true, false));
                */
                csv.WriteRecords(DoTestsForSettings(iterations, true, true, true));
                writer.Flush();
                stream.Position = 0;
                var text = reader.ReadToEnd();
                File.WriteAllText("Report.csv", text);
            }
        }
开发者ID:christofur,项目名称:SuperchargedReact.Net,代码行数:30,代码来源:Program.cs


示例9: DownloadCSVTemplate

        /// <summary>
        /// Downloads the CSV template for assignments.
        /// </summary>
        /// <author> Cristian Araya Fuentes </author>
        /// <returns> Csv file </returns>
        public FileResult DownloadCSVTemplate()
        {
            String vTemplateFileName = "plantillaAsignacion.csv";
            byte[] vFileSize;
            int vIDEntity = getEntityID(Request.Cookies["Entidad"].Value);
            int vIDPeriod = Int32.Parse(Request.Cookies["Periodo"].Value);

            IEnumerable<DataCSV> vGroups = getGroupesPeriod(vIDPeriod, vIDEntity);

            using (Stream memoryStream = new MemoryStream())
            {
                StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);

                var vWriter = new CsvWriter(streamWriter);
                vWriter.Configuration.Encoding = Encoding.UTF8;
                //Write the CSV's file header
                vWriter.WriteHeader(typeof(DataCSV));

                //Write each group
                foreach (DataCSV group in vGroups)
                {
                    vWriter.WriteRecord(group);
                }

                vWriter.NextRecord();
                streamWriter.Flush();
                memoryStream.Flush();
                memoryStream.Position = 0;
                vFileSize = new byte[memoryStream.Length];
                memoryStream.Read(vFileSize, 0, vFileSize.Length);
                streamWriter.Close();
                streamWriter.Dispose();
            }
            return File(vFileSize, System.Net.Mime.MediaTypeNames.Application.Octet, vTemplateFileName);
        }
开发者ID:saca-ae,项目名称:SACA-AE_Web-App_v2,代码行数:40,代码来源:CSVController.cs


示例10: btnOutputCsv_Click

        /// <summary>
        /// CSV出力ボタンクリック処理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOutputCsv_Click(object sender, EventArgs e)
        {
            // フォルダチェック
            if (!ExistsPath(txtFolderPath.Text)) return;

            // ファイル保存先の指定
            dlgFileSave.FileName = "tree.csv";
            dlgFileSave.Filter = "CSVファイル(*.csv)|*.csv";
            dlgFileSave.Title = "保存先のファイルを指定してください";
            dlgFileSave.RestoreDirectory = true;
            if (dlgFileSave.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // ファイル取得
            var records = ToCsvRecord(txtFolderPath.Text);

            // CSV出力
            using (var sr = new StreamWriter(dlgFileSave.FileName, false, Encoding.GetEncoding(932)))
            using (var csv = new CsvWriter(sr))
            {
                csv.Configuration.Encoding = Encoding.GetEncoding(932);
                csv.Configuration.AllowComments = false;
                csv.Configuration.HasHeaderRecord = true;
                csv.Configuration.RegisterClassMap<CsvRecordMap>();
                csv.Configuration.QuoteAllFields = true;
                csv.WriteRecords(records);
            }

            MessageBox.Show("終わったよ!");
        }
开发者ID:Ryow,项目名称:ProjectTree,代码行数:37,代码来源:MainForm.cs


示例11: GetFile

        private static byte[] GetFile()
        {
            var items = new List<Order>()
                {
                    new Order()
                        {
                            Id = 1,
                            ShippingMethodName= "Test",
                        }
                };

            using (var ms = new MemoryStream())
            using (var sw = new StreamWriter(ms))
            using (var w = new CsvWriter(sw))
            {
                w.WriteField("Order Id");
                w.WriteField("Shipping Method");
                w.WriteField("Tracking Number");
                w.NextRecord();

                foreach (var item in items)
                {
                    w.WriteField(item.Id);
                    w.WriteField(item.ShippingMethodName);
                    w.WriteField("Courier");
                    w.NextRecord();
                }

                sw.Flush();
                var file = ms.ToArray();
                sw.Close();

                return file;
            }
        }
开发者ID:neozhu,项目名称:Ecommerce,代码行数:35,代码来源:BulkShippingUpdateValidationServiceTests.cs


示例12: SaveTileMatrix

        public void SaveTileMatrix(TileType[,] map, string path)
        {
            IList<TileRecord> records = new List<TileRecord>();

            int cols = map.GetLength(0);
            int rows = map.GetLength(1);

            for (int x = 0; x < cols; x++)
            {
                for (int y = 0; y < rows; y++)
                {
                    TileType type = map[x, y];
                    TileRecord record = Mapper.Map<TileType, TileRecord>(type);

                    record.X = x;
                    record.Y = y;
                    records.Add(record);
                }
            }

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (Stream stream = File.OpenWrite(path))
            using (TextWriter textWriter = new StreamWriter(stream))
            using (CsvWriter csvWriter = new CsvWriter(textWriter))
            {
                foreach (TileRecord record in records)
                {
                    csvWriter.WriteRecord(record);
                }
            }
        }
开发者ID:bevacqua,项目名称:MarianX,代码行数:35,代码来源:Persistance.cs


示例13: ExportCategories

        public void ExportCategories(string path, bool zipIt = true)
        {
            var fileName = "Categories_" + DateTime.Now.ToString("yyyyMMddTHHmmss");
            using (var file = File.CreateText(Path.Combine(path, fileName + ".csv")))
            {
                var csv = new CsvWriter(file);
                csv.Configuration.RegisterClassMap<CategoryCsvMap>();
                csv.WriteHeader<Category>();

                foreach (var category in categoryService.FindAll().OrderBy(c => c.Id).InChunksOf(100))
                {
                    csv.WriteRecord(category);
                }
            }

            if (zipIt)
            {
                using (var zip = new ZipFile(Path.Combine(path, fileName + ".zip")))
                {
                    zip.AddFile(Path.Combine(path, fileName + ".csv"), "").FileName = "Categories.csv";
                    zip.Save();
                }

                File.Delete(Path.Combine(path, fileName + ".csv"));
            }
        }
开发者ID:alin-rautoiu,项目名称:Cart42,代码行数:26,代码来源:DataExportService.cs


示例14: WriteMultipleNamesTest

        public void WriteMultipleNamesTest()
        {
            var records = new List<MultipleNamesAttributeClass>
            {
                new MultipleNamesAttributeClass { IntColumn = 1, StringColumn = "one" },
                new MultipleNamesAttributeClass { IntColumn = 2, StringColumn = "two" }
            };

            string csv;
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var csvWriter = new CsvWriter( writer ) )
            {
                csvWriter.Configuration.AttributeMapping<MultipleNamesAttributeClass>();
                csvWriter.WriteRecords( records );

                writer.Flush();
                stream.Position = 0;

                csv = reader.ReadToEnd();
            }

            var expected = string.Empty;
            expected += "int1,string1\r\n";
            expected += "1,one\r\n";
            expected += "2,two\r\n";

            Assert.NotNull( csv );
            Assert.Equal( expected, csv );
        }
开发者ID:pwelter34,项目名称:CsvHelper,代码行数:31,代码来源:CsvWriterMappingTests.cs


示例15: writeEmailListToCSV

        private void writeEmailListToCSV(String[] emails, String CSVFileName)
        {
            try
            {
                using (var sr = new StreamWriter(@CSVFileName))
                {
                    var writer = new CsvWriter(sr);
                    /*-------------------------
                     * HEADER
                     * -----------------------*/
                    writer.WriteField("Email Address");
                    writer.NextRecord();
                    /*-------------------------
                     * Email List
                     * -----------------------*/
                    for(int i=0; i< emails.Length;i++)
                    {
                        writer.WriteField(emails[i]);
                        writer.NextRecord();
                    }

                }
            }
            catch(Exception e)
            {Console.WriteLine("CSV write failed");}
        }
开发者ID:PrezzaTechnologies,项目名称:Developer-Samples,代码行数:26,代码来源:EmailListExport.cs


示例16: GenerateCsvStub

        public void GenerateCsvStub(string targetPath)
        {
            Program.Write("Generating CSV stub ...");
            using (var stream = new StreamWriter(targetPath, false, Encoding.UTF8))
            {
                var writer = new CsvWriter(stream, CsvService.GetDefaultCsvConfiguration());

                var dummyLine = new Dictionary<string, string>();
                foreach (var column in _configuration.Columns)
                {
                    dummyLine[column.Header] = "";
                }

                foreach (var field in dummyLine.Keys)
                {
                    writer.WriteField(field);
                }
                writer.NextRecord();
                foreach (var field in dummyLine.Keys)
                {
                    writer.WriteField(dummyLine[field]);
                }
            }

            Program.Write("CSV stub saved at '" + targetPath + "'.");
        }
开发者ID:eRecruiter,项目名称:eRecruiter.ApplicantImport,代码行数:26,代码来源:CsvStubService.cs


示例17: FiltersForLineItemType

        public void FiltersForLineItemType()
        {
            // Arrange
            var sw = new StringWriter();
            using (var csv = new CsvWriter(sw))
            {
                var lineItems = new[]
                {
                    new LineItem {RecordType = "Dummy"},
                    new LineItem {RecordType = "LineItem", RecordId = "Hoojey"}
                };
                csv.WriteHeader<LineItem>();
                csv.WriteRecords(lineItems);
            }

            // Act
            List<LineItem> parsedItems;
            using (var reader = new StringReader(sw.ToString()))
            {
                using (var parser = new LineItemCsvParser(reader))
                {
                    parsedItems = parser.GetLineItems().ToList();
                }
            }

            // Assert
            parsedItems.Count.Should().Be(1);
            parsedItems[0].RecordId.Should().Be("Hoojey");
        }
开发者ID:nelsonwellswku,项目名称:stack-it-net,代码行数:29,代码来源:LineItemCsvParserTests.cs


示例18: WriteAllRecordsWithMapping

        public void WriteAllRecordsWithMapping()
        {
            var records = new List<CustomObject>
            {
                new CustomObject
                {
                    GuidColumn = new Guid("f96a1c66-4777-4642-86fa-703098065f5f"),
                    IntColumn = 1,
                    StringColumn = "one",
                    CustomTypeColumn = new CustomType
                    {
                        First = 1,
                        Second = 2,
                        Third = 3,
                    },
                },
                new CustomObject
                {
                    GuidColumn = new Guid("06776ed9-d33f-470f-bd3f-8db842356330"),
                    IntColumn = 2,
                    StringColumn = "two",
                    CustomTypeColumn = new CustomType
                    {
                        First = 4,
                        Second = 5,
                        Third = 6,
                    },
                },
            };

            Benchmark.This("CsvWriter.WriteRecords", () =>
            {
                using (var memoryStream = new MemoryStream())
                using (var streamWriter = new StreamWriter(memoryStream))
                using (var writer = new CsvWriter(streamWriter))
                {
                    writer.Configuration.RegisterClassMap<CsvHelperMappingForCustomObject>();

                    writer.WriteRecords(records);

                    streamWriter.Flush();
                }
            })
                .Against.This("FlatFileEngine.Write", () =>
                {
                    var layout = new FlatFileMappingForCustomObject();
                    using (var stream = new MemoryStream())
                    {
                        var factory = new DelimitedFileEngineFactory();

                        var flatFile = factory.GetEngine(layout);

                        flatFile.Write(stream, records);
                    }
                })
                .WithWarmup(1000)
                .For(10000)
                .Iterations()
                .PrintComparison();
        }
开发者ID:mtherien,项目名称:FlatFile,代码行数:60,代码来源:FlatFileVsCsvHelperBenchmark.cs


示例19: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = Request["MethodName"];
            string afterDate = Request["AfterDate"];

            Response.ContentType = "text/plain";
            using (SqlConnection conn = new SqlConnection(profilesdb))
            {
                conn.Open();
                SqlCommand dbcommand = new SqlCommand("[UCSF.].[ReadActivityLog]", conn);
                dbcommand.CommandType = CommandType.StoredProcedure;
                dbcommand.Parameters.Add(methodName != null ? new SqlParameter("@methodName", methodName) : new SqlParameter("@methodName", DBNull.Value));
                dbcommand.Parameters.Add(afterDate != null ? new SqlParameter("@afterDT", afterDate) : new SqlParameter("@afterDT", DBNull.Value));
                using (SqlDataReader dbreader = dbcommand.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    CsvWriter writer = new CsvWriter(Response.Output);
                    while (dbreader.Read())
                    {
                        writer.WriteField(dbreader.GetInt32(0));
                        writer.WriteField(dbreader[1].ToString());
                        writer.WriteField(dbreader[2].ToString());
                        writer.WriteField(dbreader[3].ToString());
                        writer.WriteField(dbreader.GetDateTime(4));
                        writer.WriteField(dbreader[5].ToString());
                        writer.WriteField(dbreader[6].ToString());
                        writer.WriteField(dbreader[7].ToString());
                        writer.NextRecord();
                    }
                    Response.Output.Flush();
                }
            }
        }
开发者ID:TariqStuff,项目名称:ProfilesRNS,代码行数:32,代码来源:ActivityLog.aspx.cs


示例20: Main

        private static void Main()
        {
            using (
                var client = new HttpClient {BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"])}
                )
            {
                var history = new Historian(
                    new WorkItemRepository(new TfsConnection(ConfigurationManager.AppSettings["username"],
                        ConfigurationManager.AppSettings["password"], client)));

                var burnup = history.GetBurnUpDataSince(new DateTime(2014, 7, 7, 23, 59, 59), @"BPS.Scrum\Dev -SEP Project");
                using (var writer = new StreamWriter(@".\completed" + DateTime.Now.ToString("yyyymmmmdd") + ".xls"))
                {
                    var csvWriter = new CsvWriter(writer, new CsvConfiguration { Delimiter = "\t" });

                    csvWriter.WriteRecords(burnup.First(s => s.Title == "Completed").Data);
                }

                using (var writer = new StreamWriter(@".\requested" + DateTime.Now.ToString("yyyymmmmdd") + ".xls"))
                {
                    var csvWriter = new CsvWriter(writer, new CsvConfiguration { Delimiter = "\t" });

                    csvWriter.WriteRecords(burnup.First(s => s.Title == "Requested").Data);
                }
            }
        }
开发者ID:BobNowadly,项目名称:VisualStudioDashboard,代码行数:26,代码来源:Program.cs



注:本文中的CsvWriter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Cube类代码示例发布时间:2022-05-24
下一篇:
C# CsvRow类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap