public void DataTable2Txt(DataTable dt, string fullFileName) { if (dt == null) return; try { using (FileStream fs = new FileStream(fullFileName, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs)) { for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { sw.Write(dt.Rows[i][j].ToString() + " "); } sw.WriteLine(); } sw.Close(); } } } catch { throw; } } public void DataGridView2Txt(DataGridView dgv, string fullFileName) { if (dgv == null) return; try { using (FileStream fs = new FileStream(fullFileName, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs)) { for (int j = 0; j < dgv.ColumnCount; j++) { sw.Write(dgv.Columns[j].HeaderText + " "); } sw.WriteLine(); int rowCount = dgv.RowCount; if (dgv.AllowUserToAddRows) rowCount--; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < dgv.Columns.Count; j++) { // 第一行是标题行 sw.Write(dgv[j, i].Value.ToString() + " "); } sw.WriteLine(); } sw.Close(); } } } catch { throw; } }