基于DevExpress的SpreadsheetControl实现对Excel的打开、预览、保存、另存为、打印(附源码下载)
場景
Winform控件-DevExpress18下載安裝注冊以及在VS中使用:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100061243
參照以上將DevExpress安裝并引進到工具箱。
這里使用的是VS2013所以安裝的DevExpress是14版本。
DevExpress14以及注冊機下載
https://download.csdn.net/download/badao_liumang_qizhi/11608734
效果
?
實現
環境搭建
新建Winform程序,拖拽一個SpreadsheetControl,以及一個Button按鈕。
?
然后雙擊進入打開以及預覽按鈕的點擊事件中
?private void simpleButton1_Click(object sender, EventArgs e){string filePath = FileDialogHelper.OpenExcel();if (!string.IsNullOrEmpty(filePath)){IWorkbook workbook = spreadsheetControl1.Document;workbook.LoadDocument(filePath);}}其中打開文件的路徑是有工具類FileDialogHelper中的OpenEecel方法返回的。
新建FileDialogHelper類,類中新建方法實現打開一個選擇文件對話框并將文件路徑返回。
?public static string OpenExcel(){OpenFileDialog fileDialog = new OpenFileDialog();fileDialog.Multiselect = true;fileDialog.Title = "請選擇文件";fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //設置要選擇的文件的類型if (fileDialog.ShowDialog() == DialogResult.OK){return fileDialog.FileName;//返回文件的完整路徑???????????????}else{return null;}}保存Excel實現
拖拽一個按鈕,雙擊進入其點擊事件中。
在上面預覽窗口中雙擊單元格對excel進行編輯后點擊保存會將源文件進行保存。
private void simpleButton2_Click(object sender, EventArgs e){spreadsheetControl1.SaveDocument();}Excel另存為實現
拖拽一個按鈕,然后雙擊進入其點擊事件中
?
private void simpleButton3_Click(object sender, EventArgs e){//獲取要保存的文件路徑string filePath = FileDialogHelper.SaveExcel();//如果不為空if (!string.IsNullOrEmpty(filePath)){try{//獲取預覽的excel對象 Document提供對控件中加載的工作簿的訪問IWorkbook workbook = spreadsheetControl1.Document;//根據選擇的路徑保存excelworkbook.SaveDocument(filePath);//彈窗提示MessageBox.Show("保存成功");}catch (Exception ex){MessageBox.Show(ex.Message);}}}同理使用工具類彈窗選擇保存路徑,然后調用Saveocument(path)進行保存另存為。
SaveExcel方法代碼
?public static string SaveExcel(){string filename = "霸道";SaveFileDialog saveDialog = new SaveFileDialog();//設置默認文件擴展名。saveDialog.DefaultExt = "xls";//設置當前文件名篩選器字符串,該字符串決定對話框的“另存為文件類型”或“文件類型”框中出現的選擇內容。saveDialog.Filter = "Excel文件|*.xls";//? 用默認的所有者運行通用對話框。saveDialog.ShowDialog();//如果修改了文件名,用對話框中的文件名名重新賦值filename = saveDialog.FileName;//被點了取消if (filename.IndexOf(":") < 0) return null;else{//獲取文件對話框中選定的文件名的字符串return saveDialog.FileName.ToString();}}效果
?
Excel打印實現
拖拽一個按鈕,然后雙擊進入其點擊事件中。
?private void simpleButton4_Click(object sender, EventArgs e){this.spreadsheetControl1.ShowPrintPreview();}效果
?
源碼下載
https://download.csdn.net/download/badao_liumang_qizhi/11618624
總結
以上是生活随笔為你收集整理的基于DevExpress的SpreadsheetControl实现对Excel的打开、预览、保存、另存为、打印(附源码下载)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DevExpress的PdfViewer
- 下一篇: Winforn中导入Excel并显示然后