ورود

View Full Version : ذخیره اطلاعات دیتا گرید در اکسل



helpsos
سه شنبه 17 مرداد 1391, 18:15 عصر
سلام
من از کد زیر برای اینکار استفاده می کنم ولی error می دهد

private void ExportToExcel(DataGrid gridview, string Name)
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook

Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.

// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet

worksheet.Name = "ذخیره اطلاعات";
worksheet.DisplayRightToLeft = true;

// storing header part in Excel

for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].Header.ToString();
}

// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Items.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{

worksheet.Cells[i + 2, j + 1] = ((gridview.Columns[j].GetCellContent(gridview.Items[i]) as TextBlock).Text);

}
}
string time = DateTime.Now.ToString();
time = time.Replace(":", "");
time = time.Replace("/", "");
// save the application
workbook.SaveAs("C:\\" + Name + time + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode. xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
//app.Quit();

}

این Error را می دهد:
Object reference not set to an instance of an object.

helpsos
جمعه 20 مرداد 1391, 19:20 عصر
سلام
کسی نیست کمک کنه؟؟

helpsos
شنبه 21 مرداد 1391, 19:43 عصر
وای عجب تالار فعالی تاپیک را نذاشته جواب را می دن:قهقهه:

من مجبور شدم دورش بزنم. یعنی چون گرید را با دیتاتیبل پر کرده بودم اطلاعات را از اون خواندم.
اگه کسی خواست بگه تا کدش را بزارم ولی خیلی واضحه.

morteza271
دوشنبه 16 بهمن 1391, 14:16 عصر
سلام دوست عزیز.
ممنون میشم اگه کدتون رو اینجا قرار بدین تا هم من و هم بقیه دوستان که در این زمینه مشکل دارن ازش استفاده کنن.

باتشکر