private void DirectPrint_Click(object sender, EventArgs e) { isprint = false; GenerateExcel_Click(sender, e); //使用NPOI產生excel if (newsavefilepath != "" && isprint==true) { isprint = false; ChangeExcel2Image(newsavefilepath); //利用Spire將excel轉換成圖片 if (printDialog1.ShowDialog() == DialogResult.OK) { printDocument1.Print(); //列印 } } }
private void Generate_Click(object sender, EventArgs e) { CreateExcel(); //使用NPOI產生excel內容 SaveFileDialog savedialog = new SaveFileDialog(); //彈出讓使用者選擇excel儲存路徑的視窗 savedialog.Filter = " excel files(*.xlsx)|*.xlsx|All files(*.*)|*.*"; savedialog.RestoreDirectory = true; savedialog.FileName = string.Format("銷售訂單審批單{0}", DateTime.Now.ToString("yyyyMMddHHmm")); if (savedialog.ShowDialog() == DialogResult.OK) { //newsavefilepath是excel的儲存路徑 newsavefilepath = savedialog.FileName.ToString().Trim(); using (FileStream newfs = new FileStream(newsavefilepath, FileMode.Create, FileAccess.ReadWrite)) { singlexssfwk.Write(newfs); //將產生的excel寫入使用者選擇儲存的檔案路徑中 newfs.Close(); } } }
using NPOI.XSSF.UserModel; XSSFWorkbook singlexssfwk; //注意,不同的NPOI版本調用的方法不一致,這裡使用的版本是2.1.3.1 private void CreatExcel() { //擷取模板excel的路徑 string str = System.Environment.CurrentDirectory + "\\XXXX.xlsx"; if (File.Exists(str)) { using (FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read)) { singlexssfwk = new XSSFWorkbook(fs); fs.Close(); } //擷取表 XSSFSheet xssfsheet = (XSSFSheet)singlexssfwk.GetSheetAt(0); //建立行 XSSFRow xssfrow1 = (XSSFRow)xssfsheet.GetRow(1); //設定儲存格內容 xssfrow1.GetCell(0).SetCellValue("..."); ... ... } else { .. ... } }
using Spire.Xls; public void ChangeExcel2Image(string filename) { Workbook workbook = new Workbook(); workbook.LoadFromFile(filename); Worksheet sheet = workbook.Worksheets[0]; sheet.SaveToImage(imagepath); //圖片尾碼.bmp ,imagepath自己設定 }
//在PrintPage方法中寫截取圖片 的代碼 private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { #region 如果不需要截取圖片,可以不用寫以下代碼 GC.Collect(); Graphics g = e.Graphics; //imagepath是指 excel轉成的圖片的路徑 using (Bitmap bitmap = new dBitmap(imagepath)) { //如何截取自己摸索 Rectangle newarea = new Rectangle(); newarea.X = 0; newarea.Y = 50; newarea.Width = bitmap.Width; newarea.Height = bitmap.Height - 120; using (Bitmap newbitmap = bitmap.Clone(newarea, bitmap.PixelFormat)) { g.DrawImage(newbitmap, 0, 0, newbitmap.Width - 200, newbitmap.Height - 150); } } #endregion }