本文整理汇总了C#中CsvWriter类的典型用法代码示例。如果您正苦于以下问题:C# CsvWriter类的具体用法?C# CsvWriter怎么用?C# CsvWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CsvWriter类属于命名空间,在下文中一共展示了CsvWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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();
}
}
}
示例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);
}
}
}
示例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;
}
示例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();
}
}
}
}
}
示例5: encoding_gets_encoding
public void encoding_gets_encoding()
{
using (var writer = new CsvWriter(new MemoryStream(), Encoding.ASCII))
{
Assert.Same(Encoding.ASCII, writer.Encoding);
}
}
示例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);
}
}
示例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");
}
示例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);
}
}
示例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);
}
示例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("終わったよ!");
}
示例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;
}
}
示例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);
}
}
}
示例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"));
}
}
示例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 );
}
示例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");}
}