保存为Excel
使用system.io保存,需要导入的库:using System.IO;
//使用system.io保存
//grid为整个DataGridView对象,而filePath为要保存的路径(包括后缀名),下同
public void saveExcelIO(DataGridView grid, string filePath)
{
Thread.Sleep(1000);
StreamWriter sw = new StreamWriter(filePath, false, Encoding.GetEncoding("gb2312"));
StringBuilder sb = new StringBuilder();
//写入标题
for(int k = 0; k < grid.Columns.Count; k++)
{
if (grid.Columns[k].Visible)
{
//\t相当于是在键盘上打一个tab键
sb.Append(grid.Columns[k].HeaderText.ToString().Trim() + "\t");
}
}
//换行
sb.Append(Environment.NewLine);
//开始写入每行的数值
for (int i = 0; i < grid.Rows.Count - 1; i++)
{
System.Windows.Forms.Application.DoEvents();
for(int j = 0; j < grid.Columns.Count; j++)
{
if (grid.Columns[j].Visible)
{
//单元格有一定字节的数量限制,可能会超出,超出会出现两个单元格内容一样的情况
sb.Append(grid.Rows[i].Cells[j].Value.ToString().Trim() + "\t");
}
}
sb.Append(Environment.NewLine);//换行
}
sw.Write(sb.ToString());
sw.Flush();
sw.Close();
}
保存为CSV
//保存csv
public void saveCSV(DataGridView grid,string filePath)
{
Thread.Sleep(1000);
StreamWriter sw = new StreamWriter(filePath, false, Encoding.GetEncoding("gb2312"));
string strLine = "";
//表头
for (int i = 0; i < grid.ColumnCount; i++)
{
if (i > 0)
strLine += ",";
strLine += grid.Columns[i].HeaderText;
}
strLine.Remove(strLine.Length - 1);
sw.WriteLine(strLine);
strLine = "";
for(int j = 0; j < grid.Rows.Count; j++)
{
strLine = "";
int col = grid.Columns.Count;
for(int k = 0; k < col; k++)
{
if (k > 0 && k < col)
strLine += ",";
if (grid.Rows[j].Cells[k].Value == null)
strLine += "";
else
{
string cell = grid.Rows[j].Cells[k].Value.ToString().Trim();
//防止里面有特殊符号
cell = cell.Replace("\"", "\"\"");
cell = "\"" + cell + "\"";
strLine += cell;
}
}
sw.WriteLine(strLine);
}
sw.Close();
}