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