سلام
این کدها تست شدن
بصورت تکست
SaveFileDialog Osv = new SaveFileDialog();
Osv.FileName = DateTime.Now.ToString("yyyyMMddmmss") + ".txt";
Osv.Filter = "Text File | *.txt";
//TextWriter sw = new StreamWriter(@"g:\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
if (Osv.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(Osv.OpenFile());
int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridView1.Rows[i].Cells[0].Value.ToString() + ", " + dataGridView1.Rows[i].Cells[1].Value.ToString() + "," + dataGridView1.Rows[i].Cells[2].Value.ToString() + "," + dataGridView1.Rows[i].Cells[3].Value.ToString() + "," + dataGridView1.Rows[i].Cells[4].Value.ToString() + "," + dataGridView1.Rows[i].Cells[5].Value.ToString() + "," + dataGridView1.Rows[i].Cells[6].Value.ToString() + "," + dataGridView1.Rows[i].Cells[7].Value.ToString() + "," + dataGridView1.Rows[i].Cells[8].Value.ToString() + "," + dataGridView1.Rows[i].Cells[9].Value.ToString() + "," + dataGridView1.Rows[i].Cells[10].Value.ToString());
}
sw.Close(); //Don't Forget Close the TextWriter Object(sw)
}
MessageBox.Show(" فایل ذخیره شد ");
********************************************************************************
بصورت اکسل
میبایست کلاس using Microsoft.Office.Interop.Excel;
در فضای نام اضافه کنید
try
{
_Application app = new Microsoft.Office.Interop.Excel.Application();
_Workbook workbook = app.Workbooks.Add(Type.Missing);
_Worksheet worksheet = null;
app.Visible = true;
worksheet = (Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Worksheet)workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Document(*.xlsx)|*.xlsx";
// sfd.FileName = "Export";
if (sfd.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
// Exit from the application
wait();//threadشروع
app.Quit();
}
catch (Exception)
{
throw;
}
finally
{
endwait();//هست threadاین
}