Hello...
I have a windows app where i have to save the data entered by the user in excel sheet via savefiledialog tool...but when i try to save it,it gets saved properly...but when i go to the location where i saved it,n open the file,it opens only once,next time i try to open it,error is displayed that file format or extension is incorrect...n so it cant open...
plz help...
here is my code..
Excell.Application xlApp;
Excell.Workbook xlWorkBook;
Excell.Worksheet xlWorkSheet;
Excell.Range range;
string str = "";
int rCnt = 0;
int cCnt = 0;
xlApp = new Excell.ApplicationClass();
object BlankValue = System.Reflection.Missing.Value;
string docpath = Environment.GetFolderPath(Environment.SpecialFolder
.MyDocuments);
string path1 = string.Format(docpath + @"\Report{0:yyyy_MM_dd}.xlsx",
DateTime.Now.Date);
xlWorkBook = xlApp.Workbooks.Open(path1, 0, true, 1, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excell.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
List<string> Data = new List<string>();
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excell.Range).Value2;
Data.Add(str);
}
}
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
string path2 = saveFileDialog1.FileName;
saveFileDialog1.Filter = "Excel Workbook(*.xlsx)|*.xlsx";
Excell.Application App;
Excell.Workbook WorkBook;
Excell.Worksheet WorkSheet;
App = new Excell.ApplicationClass();
WorkBook = App.Workbooks.Add(BlankValue);
WorkSheet = (Excell.Worksheet)WorkBook.Worksheets.get_Item(1);
int count = 0;
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(myStream);
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
WorkSheet.Cells[rCnt, cCnt] = Data[count];
count++;
}
}
WorkBook.SaveAs(myStream.ToString()[0], Excell.XlFileFormat
.xlWorkbookDefault, BlankValue, BlankValue, false, BlankValue,
Excell.XlSaveAsAccessMode.xlNoChange, BlankValue, BlankValue,
BlankValue, BlankValue, BlankValue);
WorkBook.Close(true, null, null);
myStream.Dispose();
wText.Dispose();
App.Quit();
}
}
}