How to Export For Loop to csv file?
You must put a delimiter between the first column and the second. Specifically, you need to change each line to combo:,
instead of just combo:
. You can fix this by inserting a comma to your print statement:
print(f"combo:, {x}, {y}")
Finally, to export it to a CSV file, you need to get a file pointer and write to it. You could do it similar to the following (merge all the data to 1 string, then write it to a file), if you plan on making a new CSV file:
fruits = ['apple', 'banana', 'kiwi']
veggies = ['corn', 'lettuce', 'spinach']
# Make a new string to put all the data in
file_data = ""
for x, y in zip(fruits, veggies):
file_data += f"combo:, {x}, {y}\n"
# Make a new file
with open("test_file.csv", "w") as f:
# Write to the file
f.write(file_data)
How to export JavaScript array info to csv (on client side)?
You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):
const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
let csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray) {
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
or the shorter way (using arrow functions):
const rows = [
["name1", "city1", "some other info"],
["name2", "city2", "more info"]
];
let csvContent = "data:text/csv;charset=utf-8,"
+ rows.map(e => e.join(",")).join("\n");
Then you can use JavaScript's window.open
and encodeURI
functions to download the CSV file like so:
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
Edit:
If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using thewindow.open
method. In order to achieve this, you can create a hidden <a>
DOM node and set its download
attribute as follows:var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
exporting list into a csv file using python
You need to convert the list object into csv object.
import csv
with open('MyList.csv', 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(MyList)
Refer the following question by Fortilan
Create a .csv file with values from a Python list
Write to CSV file and export it?
Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.
Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.
You can add the following to the (I believe this is correct) Load event:
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
sb.AppendLine(TransformDataLineIntoCsv(line));
HttpContext.Current.Response.Write(sb.ToString());
writing to the response stream code ganked from here.
Exporting Data Via CSV File
I think this CodableCSV project will be a really good starting point for you.
Here's the end of my modified createCsv()
:
let myRows = [
["Quanity", "Item", "Cost", "Total", "Total (USD)"],
[sCount, barName, sCost, sTotal, newTotal]
]
do {
let string = try CSVWriter.encode(rows: myRows, into: String.self)
print(string)
return MessageDocument(message: string)
} catch {
fatalError("Unexpected error encoding CSV: \(error)")
}
When I click on the 'Export' button, I see, from that print statement:
Quanity,Item,Cost,Total,Total (USD)
"1,600",ChocoBar,€4.95,"€7,920.00","$8,954.27"
You're going to need to be deliberate about adding title
, subTitle
, "Sale in Dollars"
because the rows they're on need to have the same number of columns as your data—CSV isn't Excel in this regard; where in Excel you can put data in any cell, no imposed structure—so something like:
let myRows = [
["Henry's Chocolate Sales Frankfurt", "", "", ""], // 3 empty (placeholder) columns
...
]
AWS Forecast Export - Create Only One CSV File?
I have the same question, looks like the feature is not ready yet. you have to create a separate service with athena to export single csv file. Please refer here from AWS: https://repost.aws/questions/QUMOGKLulFRjuSUTLkJ4B7dQ/aws-forecast-export-create-only-one-csv-file
The AWS Forecast service does not currently have a method to reduce the number of output files using the console, CLI, or the SDK. The service is designed in such a way that it dynamically calculates the number of output CSV files.
A feature request exists for exporting data to a single file but I am unable to provide an ETA of when/if such a feature would be implemented. To work around this, you may consider using the “Improving Forecast Accuracy with Machine Learning” solution (1) to create an aggregated view of all your forecast data (inputs and outputs), query your forecast output within AWS Athena, and then export the query results as a single CSV.
Resources: (1). https://aws.amazon.com/solutions/implementations/improving-forecast-accuracy-with-machine-learning/
Writing data into CSV file in C#
UPDATE
Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.
CSV is way more complicated than what the question/answer suggests.
Original Answer
As you already have a loop, consider doing it like this:
//before your loop
var csv = new StringBuilder();
//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);
//after your loop
File.WriteAllText(filePath, csv.ToString());
Or something to this effect.
My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.
You can replace
File.WriteAllText(filePath, csv.ToString());
with
File.AppendAllText(filePath, csv.ToString());
if you want to keep previous versions of csv in the same file
C# 6
If you are using c# 6.0 then you can do the following
var newLine = $"{first},{second}"
EDIT
Here is a link to a question that explains what Environment.NewLine
does.
Related Topics
What Is the Meaning of "This" in C#
In .Net 4.0, How to 'Sandbox' an In-Memory Assembly and Execute a Method
Get All Associate/Composite Objects Inside an Object (In Abstract Way)
Why Can't I Use Interface with Explicit Operator
How to Use Acrylic Accent in Windows 10 Creators Update
ASP.NET Identity Cookie Across Subdomains
Is There a Port of Memcache to .Net
How to Partially Project a Child Object with Many Fields in Nhibernate
Error Message "Cs5001 Program Does Not Contain a Static 'Main' Method Suitable for an Entry Point"
How to Change Route to Username After Logged In
How to Add Code Outside the Scope of Main When Using C# 9 Top Level Statements
Openfiledialog Can't Load CSV Files But Can Load Xls/Xlsx Excel Files
C# Marking Class Property as Dirty