将datagridveiw值保存为csv文件或excel文件格式

将datagridveiw值保存为csv文件或excel文件格式

本文介绍了将datagridveiw值保存为csv文件或excel文件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发人员,

我是沙尔玛·沙尔
我正在使用数据集将csv文件加载到datagridview中,并对它们执行一些操作.毕竟,我想将datagridview保存为csv文件格式,如果用户想要使用excel格式.

我打开了一个对话框,以csv文件或excel文件格式保存数据.
问题是我没有代码将datagridview保存为csv文件或excel文件格式.

如果用户要在任何位置保存具有相同文件名或其他名称的数据,我还希望以前的csv文件名自动显示在保存"对话框中.

请立即提供解决方案

Hi developers,

I am vishal sharma
I''m loading a csv file into datagridview using dataset and perform some operation on them. After all that I want to save the datagridview in csv file format and if user wants to the excel format.

I''ve taken a dialogbox to save data in csv file or excel file format.
A problem is that I have no code to save datagridview in csv file or excel file format.

I also want that a previous csv file name automatically show in the save dialogbox if the user wants to save data with same file name or a orther name, at any location.

Please provide a solution immediatly

推荐答案

private void button1_Click(object sender, EventArgs e)
{
string strValue = string.Empty;
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
{
if (!string.IsNullOrEmpty(dataGridView1[j, i].Value.ToString()))
{
if (j > 0)
strValue = strValue + "," + dataGridView1[j, i].Value.ToString();
else
{
if (string.IsNullOrEmpty(strValue))
strValue = dataGridView1[j, i].Value.ToString();
else
strValue = strValue + Environment.NewLine + dataGridView1[j, i].Value.ToString();
}
}
}
// strValue = strValue + Environment.NewLine;
}
string strFile = @"C:\YourCSVFile.csv";
if (File.Exists(strFile)&& !string.IsNullOrEmpty(strValue))
{
File.WriteAllText(strFile, strValue);
}
}
}



或者,您可以 [ ^ ]国内文章会进一步有用.

如果有帮助,请 投票 接受答案 .



Or you can have THIS[^] domestic article to be further useful.

Please vote and Accept Answer if it Helped.



这篇关于将datagridveiw值保存为csv文件或excel文件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:43