[问题]从Data Grid view 作EXCE 读写存盘

楼主: cowuabc (阿辰)   2018-07-03 14:18:32
想请问各路高手..小弟在Data gridview 想做原有excel 的档案读取/编辑/储存
但是每次储存后,开启Excel 都会是Data gridview 里面显示的格式...
想请问各位高手有没有办法可以作保持原有excel 的格式又可以在Datagridview
作编辑以及写入原有格式...下列是小弟的练习sample...
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text files (*.xlsx)|*.xlsx|All files
(*.*)|*.*";
saveFileDialog1.Title = "Save as";
saveFileDialog1.ShowDialog();
// System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
//switch(saveFileDialog1.FilterIndex)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet =
(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = dataGridView1[j,
i].Value.ToString();
}
}
xlWorkBook.SaveAs(saveFileDialog1.FileName,
Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue,
misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
作者: johnpage (johnpage)   2018-07-03 16:56:00
内崁excel, 不要用呼叫的

Links booklink

Contact Us: admin [ a t ] ucptt.com