资源描述:
《C#中spreadsheet的使用》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C#中spreadsheet的使用1.C#用spreadsheet打开excel文件usingSystem.IO;usingMicrosoft.Office.Core;usingExcel=Microsoft.Office.Interop.Excel;publicboolOpenExcelInSpreadSheet(){ OpenFileDialogopenFileDialog=newOpenFileDialog(); openFileDialog.Filter="Excel文件(*.xls)
2、*.xls
3、所有文件(*.*)
4、
5、*.*"; openFileDialog.Title="选择要打开的文件"; openFileDialog.ShowDialog(); if(openFileDialog.FileName.Length>0) { //将原文件拷贝一份到临时文件夹再打开备份文件,不推荐直接打开原文件,因为有可能该文件已经被打开了。 //也不推荐将excel文件转换成xml文件再用spreadsheet打开,因为有的版本的excel格式转换到xml后不能正确打开。 //本例临时文件夹为应用程序所在目录的“tempexcelfiles”文件夹
6、。 stringpath=System.Windows.Forms.Application.ExecutablePath; FileInfoexeInfo=newFileInfo(path); path=exeInfo.DirectoryName+"\"; stringtempExcel=path+"tempexcelfiles\"+openFileDialog.FileName.Split(newChar[]{'\'}).Last(); if(File.Exists(tempExcel)) { stri
7、ngjust_name=ofd.FileName.Split(newChar[]{'\'}).Last(); DialogResultresult=MessageBox.Show(just_name+"已经存在,确认覆盖?","文件上传提示",MessageBoxButtons.OKCancel); if(result==DialogResult.OK) { File.Copy(ofd.FileName,tempExcel,true); Excel.Applicationapp=newExcel.Ap
8、plication(); if(app==null) { MessageBox.Show("Excel打开失败!"); returnfalse; } app.Visible=false; app.UserControl=true; Excel.Workbooksworkbooks=app.Workbooks; Excel._Workbookworkbook=workbooks.Open(newFileName,0,true,5,"","",true,Excel.XlPl
9、atform.xlWindows,"t",false,false,0,true,null,null); app.DisplayAlerts=false; try { app.CopyObjectsWithCells=true; Excel._Worksheetsheet1=(Excel._Worksheet)workbook.Sheets[1]; //打开sheet1 sheet1.UsedRange.Copy(Type.Missing); //复制sheet
10、1到剪贴板 AxMicrosoft.Office.Interop.Owc11.AxSpreadsheetspreadsheet=newAxMicrosoft.Office.Interop.Owc11.AxSpreadsheet(); spreadsheet.get_Range(this.spreadsheet.Cells[1,1]).Paste(); //将剪贴板复制的内容贴到spreadsheet上 } catch(System.Exceptionexc) { MessageB
11、ox.Show(exc.Message); returnfalse; } app.Quit(); File.Delete(tempExcel); returntrue; }else { returnfalse; } } }}