将GridView数据导出到CSV [英] export gridview data to csv
问题描述
我正在使用C#创建Windows窗体.我需要将数据gridview的数据以csv格式保存在本地驱动器上.
我已使用字符串生成器保存文件.我几乎可以做到这一点,但是存在一个问题,当我将文件保存为csv格式时,它会忽略在gridview中完成的所有格式设置,例如我已将gridview的datetime列的格式设置为dd/mm/yy hh:mm:ss,但是保存后,它以dd.mm.yy hh:mm:ss格式显示日期.
我不想在excel中手动设置其格式,我只想通过编码使其成为可能.我正在向您发送我正在使用的导出功能.
任何帮助将不胜感激.
Hi,
I am creating a windows form using C#. I need to save the data of data gridview on my local drive in csv format.
I have used string builder to save the file. I am pretty much able to do this but there is an issue that when I save my file in csv format it ignores all the formatting done in gridview, e.g. I have set the format of datetime column of gridview as dd/mm/yy hh:mm:ss but after being saved it is showing the date in format dd.mm.yy hh:mm:ss
I don''t want to format it manually in excel, I want to make it possible through coding only. I am sending you my export function which I am using.
Any help will be appreciated.
public void Export()
{
try
{
string strColumn = string.Empty;
string strRow = string.Empty;
StringBuilder objSB = new StringBuilder();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
strColumn += (i >= dataGridView1.Columns.Count - 1) ? dataGridView1.Columns[i].Name : dataGridView1.Columns[i].Name + ",";
}
objSB.AppendLine(strColumn);
for (int i = 1; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
strRow += (j >= dataGridView1.Columns.Count - 1) ? dataGridView1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") : dataGridView1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") + ",";
}
objSB.AppendLine(strRow);
strRow = string.Empty;
}
File.AppendAllText(txtFileName.Text, objSB.ToString());
MessageBox.Show("The CSV File Is Created");
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
请帮助我提供适当的代码,因为我在该领域还很陌生.
Please help me with the proper code as I am quite new in this field.
推荐答案
检查此链接,
导出为Csv [
Hi,
check this link,
Export to Csv[-]
您需要对DateTime列进行特殊处理.保存此列时,请勿使用:
You will need a special handling for the DateTime column. When saving this column you should not use:
dataGridView1.Rows[i].Cells[j].Value.ToString()
相反,您应该使用正确的DateTime格式.
这是您可能要用来在文件中获取正确的DateTime格式的格式字符串的列表:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx [ ^ ]
因此,您应该使用类似以下内容的内容:
instead you should use proper DateTime formatting.
Here is a list of format strings you might want to use to get the correct DateTime Format in your file:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^]
So, you should use something like:
dataGridView1.Rows[i].Cells[j].Value.ToString("dd/mm/yy hh:mm:ss");
为您的日期时间列.
for your datetime column.
这篇关于将GridView数据导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!