C#将datagridview导出为本地文件
将文件导出为txt,代码的大致流程是遍历 DataGridView 的行和单元格,然后将数据拼接为一个字符串 data
,再将该字符串写入到一个文本文件中。
void exToTxt(string path)
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string data = "";
foreach (DataGridViewRow row in dgvLog.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
//获取单元格所在的列索引
int cellIndex = cell.ColumnIndex;
//通过列索引得到对应的列名
string columnName = dgvLog.Columns[cellIndex].HeaderText;
//获取对应的值
string value = cell.Value.ToString();
data += columnName + ":" + value + " ";
}
data += "\r\n";
}
// 检查文件夹是否存在,如果不存在则创建文件夹
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
// 创建一个 Stream writer 对象来写入文件
using (FileStream fs = new FileStream(path + "\\text.txt", FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.WriteLine(data);
}
}
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds}毫秒");
}
但是,当要存十万条数据时,这种方法会非常的慢,故可以采用stringbuilder来构建
void ExportToTxt(string path)
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
StringBuilder data = new StringBuilder();
foreach (DataGridViewRow row in dgvLog.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
// 获取单元格所在的列索引
int cellIndex = cell.ColumnIndex;
// 通过列索引得到对应的列名
string columnName = dgvLog.Columns[cellIndex].HeaderText;
// 获取对应的值,处理空单元格
string value = cell.Value != null ? cell.Value.ToString() : "";
data.Append(columnName + ":" + value + " ");
}
data.AppendLine(); // 换行
}
// 检查文件夹是否存在,如果不存在则创建文件夹
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
// 创建一个 Stream writer 对象来写入文件
using (FileStream fs = new FileStream(Path.Combine(path, "text.txt"), FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.Write(data.ToString());
}
}
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds}毫秒");
}
导出为excel表格
第一种方法:使用 Microsoft Excel 的 COM 互操作来将 DataGridView 中的数据导出到 Excel 文件中。
void exToExcel1(string path)
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// 创建一个新的excel应用程序对象
Excel.Application excelApp = new Excel.Application();
//设置为不可见,操作在后台执行,为 true 的话会打开 Excel
excelApp.Visible = false;
//创建一个新的工作簿
Excel.Workbook workbook = excelApp.Workbooks.Add();
//创建一个工作表
Excel.Worksheet worksheet = workbook.Sheets[1];
worksheet.Name = "Log";
//生成列名
for (int i = 1; i <= dgvLog.ColumnCount; i++)
{
string ColumnName = dgvLog.Columns[i - 1].HeaderText;
worksheet.Cells[1, i] = ColumnName;
}
int rowIndex = 2;
//将datagrideview的数据保存到数据表格中
foreach (DataGridViewRow row in dgvLog.Rows)
{
if (!row.IsNewRow)
{
int colIndex = 1;
foreach (DataGridViewCell cell in row.Cells)
{
worksheet.Cells[rowIndex, colIndex] = cell.Value;
colIndex++;
}
rowIndex++;
}
}
workbook.SaveAs(path + $"/myExcelFile{DateTime.Now.ToString("ss")}.xlsx");
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds}毫秒");
try
{
workbook.Close();
}
catch (Exception)
{
throw;
}
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
这种操作也就是一个单元格一个单元格的操作,故执行效率非常的低。
第二种方法:使用了 NPOI 库创建了一个 HSSFWorkbook 对象表示一个 Excel 工作簿,然后在工作簿中创建了一个表格并将 DataGridView 中的数据写入表格中。最后,将数据写入文件并保存。
void exToExcel2(string path)
{
try
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//创建工作簿
IWorkbook workbook = new HSSFWorkbook();
//创建一个 sheet 表
ISheet sheet = workbook.CreateSheet();
int RowCount = 1;
//生成列名
IRow irowhead = sheet.CreateRow(0);
for (int i = 0; i <dgvLog.ColumnCount; i++)
{
string ColumnName = dgvLog.Columns[i].HeaderText;
ICell icell= irowhead.CreateCell(i+1);
icell.SetCellValue(ColumnName);
}
foreach (DataGridViewRow row in dgvLog.Rows)
{
int ColumnCount = 1;
//跳过第一行,第一行为列名
IRow irow = sheet.CreateRow(RowCount);
foreach (DataGridViewCell cell in row.Cells)
{
ICell icell=irow.CreateCell(ColumnCount);
icell.SetCellValue(cell.Value.ToString());
ColumnCount++;
}
RowCount++;
}
//创建文件
FileStream file = new FileStream(path + $"/myExcelFile{DateTime.Now.ToString("ss")}.xlsx", FileMode.Create, FileAccess.Write);
//创建一个 IO 流
MemoryStream ms = new MemoryStream();
//写入到流
workbook.Write(ms);
//转换为字节数组
byte[] bytes = ms.ToArray();
file.Write(bytes, 0, bytes.Length);
// 立即将数据写入文件,而不是等待缓冲区满或文件关闭
file.Flush();
//释放资源
bytes = null;
ms.Close();
ms.Dispose();
file.Close();
file.Dispose();
sheet = null;
workbook = null;
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds}毫秒");
}
catch (Exception)
{
throw;
}
}
第三种方法:使用了 StreamWriter
将 DataGridView 中的数据写入到一个 Excel 文件中,其中使用了 StringBuilder
来构建要写入的数据。
void exToExcel3(string path)
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//创建文件
FileStream file = new FileStream(path + $"/myExcelFile{DateTime.Now.ToString("ss")}.xlsx", FileMode.Create, FileAccess.Write);
//以指定的字符编码向指定的流写入字符
StreamWriter writer = new StreamWriter(file,Encoding.GetEncoding("GB2312"));
StringBuilder strbu = new StringBuilder();
//写入标题
for (int i = 0; i < dgvLog.Columns.Count; i++)
{
strbu.Append(dgvLog.Columns[i].HeaderText + "\t");
}
//加入换行符
//strbu.Append('\n');
strbu.Append(Environment.NewLine);
//写入内容
for (int i = 0; i < dgvLog.Rows.Count; i++)
{
for (int j = 0; j < dgvLog.ColumnCount; j++)
{
strbu.Append(dgvLog.Rows[i].Cells[j].Value);
strbu.Append("\t");
}
strbu.Append(Environment.NewLine);
}
writer.Write(strbu.ToString());
writer.Flush();
file.Flush();
writer.Close();
writer.Dispose();
file.Close();
file.Dispose();
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds} 毫秒");
}
第四种方法
void exToExcel4(string path)
{
// 创建 Stopwatch 对象
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//创建文件
FileStream file = new FileStream(path + $"/myExcelFile{DateTime.Now.ToString("ss")}.xlsx", FileMode.Create, FileAccess.Write);
//创建一个内存流
/* MemoryStream ms = new MemoryStream();
*/
StringBuilder strbu = new StringBuilder();
//写入标题
for (int i = 0; i < dgvLog.Columns.Count; i++)
{
strbu.Append(dgvLog.Columns[i].HeaderText + "\t");
}
//加入换行符
//strbu.Append('\n');
strbu.Append(Environment.NewLine);
//写入内容
for (int i = 0; i < dgvLog.Rows.Count; i++)
{
for (int j = 0; j < dgvLog.ColumnCount; j++)
{
strbu.Append(dgvLog.Rows[i].Cells[j].Value);
strbu.Append("\t");
}
strbu.Append(Environment.NewLine);
}
byte[] data =Encoding.UTF8.GetBytes(strbu.ToString());
/* ms.Write(data, 0, data.Length);
ms.WriteTo(file);*/
//file.Write(strbu.ToString(), 0, strbu.ToString().Length);
file.Write(data, 0, data.Length);
//转换为字节数组
/* ms.Close();
ms.Dispose();*/
file.Close();
file.Dispose();
stopwatch.Stop();
MessageBox.Show($"导出成功!导出时间为{stopwatch.ElapsedMilliseconds} 毫秒");
}