void PrintMyExcelFile(string path) { Excel.Application excelApp = new Excel.Application(); // Open the Workbook: Excel.Workbook wb = excelApp.Workbooks.Open( @path, Type.Missing, Type.Missing, Type.Missing, Global.Connect(), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Get the first worksheet. // (Excel uses base 1 indexing, not base 0.) Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1]; // Print out 1 copy to the default printer: ws.PrintOut( Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Cleanup: GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(ws); wb.Close(false, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(wb); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); }
private void PrintExcelReport(string path) { Excel.Application excelApp = new Excel.Application(); Excel.Workbook wb = excelApp.Workbooks.Open( path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1]; var printers = System.Drawing.Printing.PrinterSettings.InstalledPrinters; int printerIndex = 0; foreach (String s in printers) { if (s.Equals("Name of Printer")) { break; } printerIndex++; } ws.PrintOut(1, 2, 1, false, printers[printerIndex], true, false, Type.Missing); }
public static void PrintExcelFile(string filePath, ref string szErr) { Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); try { xlApp.Visible = true; object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, 0, true, 5, oMissing, oMissing, true, 1, oMissing, false, false, oMissing, false, oMissing, oMissing); Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets[1]; //xlWorksheet.PrintPreview(null); //xlWorksheet.PrintPreview(true); //xlApp.Visible = false; //xlWorksheet = null; xlWorksheet.PrintOut(1, 1, 2, true);//.PrintOutEx() } catch (Exception ex) { szErr = ex.ToString(); } finally { IntPtr t = new IntPtr(xlApp.Hwnd); xlApp = null; GC.Collect(); int k = 0; GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用 p.Kill(); //关闭进程k } }
public void PrintXls(string fileName) { FileInfo fileInfo = new FileInfo(fileName); Excel.Application excelApp = new Excel.Application(); if (excelApp == null) { Console.WriteLine("ERROR: Excel couldn't be started!"); return; } excelApp.Visible = false; excelApp.UserControl = true; object missing = Type.Missing; Excel.Workbook wb = excelApp.Application.Workbooks.Open(fileName); if (wb == null) { Console.WriteLine("ERROR: wb == null!"); return; } for (int index = 1; index <= wb.Sheets.Count; index++) { Excel.Worksheet workSheet = (Excel.Worksheet)wb.Worksheets.Item[index]; //------------------------打印页面相关设置--------------------------------// workSheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4; //纸张大小 workSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlPortrait; //页面竖向 /* * workSheet.PageSetup.Zoom = 75; //打印时页面设置,缩放比例百分之几 * workSheet.PageSetup.Zoom = false; //打印时页面设置,必须设置为false,页高,页宽才有效 * workSheet.PageSetup.FitToPagesWide = 1; //设置页面缩放的页宽为1页宽 * workSheet.PageSetup.FitToPagesTall = false; //设置页面缩放的页高自动 * workSheet.PageSetup.CenterFooter = "第 &P 页,共 &N 页";//页面下标 * workSheet.PageSetup.FooterMargin = 5; * workSheet.PageSetup.PrintGridlines = false; //打印单元格网线 * workSheet.PageSetup.TopMargin = 15; //上边距为2cm(转换为in) * workSheet.PageSetup.BottomMargin = 20; //下边距为1.5cm * workSheet.PageSetup.LeftMargin = 30; //左边距为2cm * workSheet.PageSetup.RightMargin = 30; //右边距为2cm * workSheet.PageSetup.CenterHorizontally = true; //文字水平居中 */ string leftHeader = fileInfo.Name + "_" + workSheet.Name; workSheet.PageSetup.LeftHeader = leftHeader; string pdfFile = fileInfo.Directory.FullName + "\\" + leftHeader + ".pdf"; workSheet.PrintOut(Preview: false, PrintToFile: true, PrToFileName: pdfFile); //workSheet.PrintOutEx(Preview: false, PrintToFile: true, PrToFileName: pdfFile); } KillProcess(excelApp); //杀掉生成的进程 GC.Collect(); //垃圾回收机制 }
/// <summary> /// Prints all the worksheets /// </summary> public void PrintAllWorksheets(int copies) { int count = WorksheetCount; for (int i = 1; i < count + 1; i++) { Excel.Worksheet worksheetPrint = (Excel.Worksheet)sheets.get_Item(i); worksheetPrint.PrintOut(missing, missing, copies, missing, true, missing, missing, missing); } }
internal void Print() { object misValue = System.Reflection.Missing.Value; xlSh.Columns.AutoFit(); xlSh.PrintOut(1, 1, 1, false, misValue, misValue, misValue, misValue); Dispose(); }
static void PrintExcelToPDF(string ExcelFilePath) { //Create a UDC object and get its interfaces IUDC objUDC = new APIWrapper(); IUDCPrinter Printer = objUDC.get_Printers("Universal Document Converter"); IProfile Profile = Printer.Profile; //Use Universal Document Converter API to change settings of converterd document Profile.PageSetup.ResolutionX = 600; Profile.PageSetup.ResolutionY = 600; Profile.FileFormat.ActualFormat = FormatID.FMT_PDF; Profile.FileFormat.PDF.ColorSpace = ColorSpaceID.CS_TRUECOLOR; Profile.FileFormat.PDF.Multipage = MultipageModeID.MM_MULTI; Profile.OutputLocation.Mode = LocationModeID.LM_PREDEFINED; Profile.OutputLocation.FolderPath = @"c:\UDC Output Files"; Profile.OutputLocation.FileName = @"&[DocName(0)] -- &[Date(0)] -- &[Time(0)].&[ImageType]"; Profile.OutputLocation.OverwriteExistingFile = false; Profile.PostProcessing.Mode = PostProcessingModeID.PP_OPEN_FOLDER; //Create a Excel's Application object Excel.Application ExcelApp = new Excel.ApplicationClass(); Object ReadOnly = true; Object Missing = Type.Missing; //This will be passed when ever we don’t want to pass value //If you run an English version of Excel on a computer with the regional settings are configured for a non-English language, you must set the CultureInfo prior calling Excel methods. System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); //Open the document from a file Excel.Workbook Workbook = ExcelApp.Workbooks.Open(ExcelFilePath, Missing, ReadOnly, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing); //Change active worksheet settings and print it Excel.Worksheet Worksheet = (Excel.Worksheet)Workbook.ActiveSheet; Excel.PageSetup PageSetup = Worksheet.PageSetup; PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; Object Preview = false; Worksheet.PrintOut(Missing, Missing, Missing, Preview, "Universal Document Converter", Missing, Missing, Missing); //Close the spreadsheet without saving changes Object SaveChanges = false; Workbook.Close(SaveChanges, Missing, Missing); //Close Microsoft Excel ExcelApp.Quit(); }
public void printFacture() { try { createFacture(); /* *@param From : The number of the page at which to start printing. If this argument is omitted, printing starts at the beginning. *@param To : The number of the last page to print. If this argument is omitted, printing ends with the last page. *@param Copies : The number of copies to print. If this argument is omitted, one copy is printed. *@param Preview : True to have Microsoft Excel invoke print preview before printing the object. False (or omitted) to print the object immediately *@param ActivePrinter : Sets the name of the active printer. *@param PrintToFile : True to print to a file. If PrToFileName is not specified, Microsoft Excel prompts the user to enter the name of the output file. *@param Collate : True to collate multiple copies. *@param PrToFileName : If PrintToFile is set to True, this argument specifies the name of the file you want to print to. */ mWorkSheets.PrintOut(1, 1, 1, false, printName, false, false, misValue); //close files mWorkBook.Close(false, misValue, misValue); oXL.Quit(); //release file releaseObject(mWorkSheets); releaseObject(mWorkBook); releaseObject(oXL); } catch (Exception e) { try { //close files mWorkBook.Close(false, misValue, misValue); oXL.Quit(); //release file releaseObject(mWorkSheets); releaseObject(mWorkBook); releaseObject(oXL); } catch { } } }
public void printLecture() { if (error == 0) { try { createLecture(); //determine le nombre de pages int nbpage = (listUsedTypeArticle.Count < 24) ? 1 : 2; /* *@param From : The number of the page at which to start printing. If this argument is omitted, printing starts at the beginning. *@param To : The number of the last page to print. If this argument is omitted, printing ends with the last page. *@param Copies : The number of copies to print. If this argument is omitted, one copy is printed. *@param Preview : True to have Microsoft Excel invoke print preview before printing the object. False (or omitted) to print the object immediately *@param ActivePrinter : Sets the name of the active printer. *@param PrintToFile : True to print to a file. If PrToFileName is not specified, Microsoft Excel prompts the user to enter the name of the output file. *@param Collate : True to collate multiple copies. *@param PrToFileName : If PrintToFile is set to True, this argument specifies the name of the file you want to print to. */ mWorkSheets.PrintOut(1, nbpage, 1, false, printName, false, false, misValue); //close files mWorkBook.Close(false, misValue, misValue); oXL.Quit(); //release file releaseObject(mWorkSheets); releaseObject(mWorkBook); releaseObject(oXL); } catch (Exception e) { if (error == 0) { MessageBox.Show("Erreur lors de la demande d'impression : " + e); } error = 1; } } }
private void printMyExcelFile() { Excel.Application application = new Excel.Application(); Excel.Workbook workbook1 = application.Workbooks.Open("D:\\MasterList.xlsx"); Excel.Worksheet worksheet1 = workbook1.ActiveSheet; try { //var print = application.ActivePrinter; //var work = workbook1; //printMyExcelFile(); worksheet1.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; worksheet1.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch { } application.Quit(); }
private void Print(Excel.Worksheet myExcelWorkSheet, Excel.Workbook myExcelWorkbook) { myExcelWorkSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape; myExcelWorkSheet.PageSetup.LeftMargin = myExcelWorkSheet.PageSetup.LeftMargin / 4; myExcelWorkSheet.PrintOut( Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Cleanup: GC.Collect(); GC.WaitForPendingFinalizers(); myExcelWorkbook.Close(false, Type.Missing, Type.Missing); //Marshal.FinalReleaseComObject(myExcelWorkSheet); //myExcelWorkSheet.Close(false, Type.Missing, Type.Missing); //Marshal.FinalReleaseComObject(myExcelWorkSheet); //APP.Quit(); //Marshal.FinalReleaseComObject(APP); }
private void button2_Click(object sender, EventArgs e) { Zachistka = textBox7.Text; Zachistka2 = textBox8.Text; Zachistka3 = textBox9.Text; ////Некоторая информация была удалена во избежании утечки конфидециальных данных login1 = SystemInformation.UserName; Dictionary <string, int> Txns = new Dictionary <string, int>(); Txns.Clear(); Txns = null; GC.Collect(); int p = 0; string ConStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + arr + ";" + "Extended Properties=\"Excel 8.0; HDR=NO; IMEX=1\""; System.Data.DataSet ds = new System.Data.DataSet("EXCEL"); OleDbConnection cn = new OleDbConnection(ConStr); try { cn.Open(); } catch (Exception) { MessageBox.Show("Проверьте правильность выбора файла и повторите попытку"); return; } System.Data.DataTable schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); string sheet1; try { for (int i2 = 0; ; i2++) { sheet1 = (string)schemaTable.Rows[i2].ItemArray[2]; } } catch (Exception) { } sheet1 = (string)schemaTable.Rows[p].ItemArray[2]; string select = String.Format("SELECT * FROM [{0}]", sheet1); OleDbDataAdapter ad = new OleDbDataAdapter(select, cn); ad.Fill(ds); System.Data.DataTable tb = ds.Tables[0]; int kek = 1; int l = 0; m1: if (l > 2000) { MessageBox.Show("Проверьте правильность данных и повторите попытку"); return; } try { for (int i = 0; ; i++) { HHv2 = HHv2 + ";" + Convert.ToString(tb.Rows[l].ItemArray[i]); } } catch (Exception) { try { wordsv2 = HHv2.Split(new char[] { ';' }); } catch (Exception) { } } if (kek == 1 && (textBox1.Text != null && textBox1.Text != "")) { if (wordsv2[5] == textBox1.Text && (Two1 == null || Two1 == "") && kek == 1) { Two1 = wordsv2[2]; Three1 = wordsv2[3]; Four1 = wordsv2[4]; Five1 = wordsv2[5]; Six1 = wordsv2[6]; Nine1 = wordsv2[9]; Ten1 = wordsv2[10]; l = 0; kek++; } else { HHv2 = null; l++; goto m1; } } if (kek == 2 && (textBox2.Text != null && textBox2.Text != "")) { if (wordsv2[5] == textBox2.Text && (Two2 == null || Two2 == "") && kek == 2) { Two2 = wordsv2[2]; Three2 = wordsv2[3]; Four2 = wordsv2[4]; Five2 = wordsv2[5]; Six2 = wordsv2[6]; Nine2 = wordsv2[9]; Ten2 = wordsv2[10]; l = 0; kek++; } else { HHv2 = null; l++; goto m1; } } if (kek == 3 && (textBox3.Text != null && textBox3.Text != "")) { if (wordsv2[5] == textBox3.Text && (Two3 == null || Two3 == "") && kek == 3) { Two3 = wordsv2[2]; Three3 = wordsv2[3]; Four3 = wordsv2[4]; Five3 = wordsv2[5]; Six3 = wordsv2[6]; Nine3 = wordsv2[9]; Ten3 = wordsv2[10]; kek++; } else { HHv2 = null; l++; goto m1; } } PRD(); Excel.Application excelApp = new Excel.Application(); Excel.Workbook wb = excelApp.Workbooks.Open(@"H:\PrintSJ.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[k]; ws.PageSetup.PrintHeadings = false; ws.PageSetup.BlackAndWhite = false; ws.PageSetup.PrintGridlines = false; ws.PageSetup.PrintTitleRows = "$1:$2"; ws.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(ws); wb.Close(false, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(wb); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); System.IO.File.Delete(@"H:\PrintSJ.xlsx"); System.Windows.Forms.Application.Restart(); return; }
public void PrintOrder(string path, System.Data.DataTable datatable, int LorR) { //Excel模板文件 string strFilePath = path; if (!File.Exists(strFilePath)) { throw new Exception("Excel条码模版不存在,无法导出"); } //定义 Microsoft.Office.Interop.Excel.Application xlApp = new Excel.Application(); if (xlApp == null) { throw new Exception("无法创建Excel对象,可能您的电脑未安装Excel"); } xlApp.Visible = false; xlApp.UserControl = true; xlApp.DisplayAlerts = false; Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Excel.Workbook workbook = workbooks.Add(strFilePath); //目标文件 Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1 //赋值 System.Data.DataTable dt = datatable; if (dt.Rows.Count > 0) { if (Convert.ToInt32(dt.Rows[0]["LorR"]) == 0) { worksheet.Cells[1, 1] = "【左】"; //左座椅还是右 } else { worksheet.Cells[1, 1] = "【右】"; } string carType = dt.Rows[0]["CarType"].ToString(); worksheet.Cells[2, 2] = carType + "座椅分装单"; //第一行 worksheet.Cells[4, 2] = dt.Rows[0]["ProductNo"].ToString(); //第二行 BLL.T_JISA t_JISA = new T_JISA(); string JISASer = t_JISA.GetJISASer(dt.Rows[0]["ProductNo"].ToString()); worksheet.Cells[5, 2] = JISASer; worksheet.Cells[6, 2] = dt.Rows[0]["CreateTime"].ToString(); //第二行 //worksheet.Cells[8,2] = dt.Rows[0]["ProductNo"].ToString(); //第二行 worksheet.Cells[11, 2] = dt.Rows[0]["CarModelName"].ToString(); //第二行 worksheet.Cells[13, 2] = dt.Rows[0]["Color"].ToString() + dt.Rows[0]["ColorCode"].ToString(); //第二行 int row = 15; if (dt.Rows[0]["MasterBarCodeL"].ToString() != "") { worksheet.Cells[row++, 2] = "左前"; } if (dt.Rows[0]["MasterBarCodeR"].ToString() != "") { worksheet.Cells[row++, 2] = "右前"; } if (dt.Rows[0]["MasterBarCodeC"].ToString() != "") { worksheet.Cells[row++, 2] = "后座椅整垫"; } if (dt.Rows[0]["MasterBarCode40"].ToString() != "") { worksheet.Cells[row++, 2] = "后背40%"; } if (dt.Rows[0]["MasterBarCode60"].ToString() != "") { worksheet.Cells[row++, 2] = "后背60%"; } if (dt.Rows[0]["MasterBarCodeB"].ToString() != "") { worksheet.Cells[row++, 2] = "后整背"; } DataMatrix.net.DmtxImageEncoder dataMatix = new DataMatrix.net.DmtxImageEncoder(); string QRCodepath = ""; if (LorR == 0) { Bitmap dataMatixCode = dataMatix.EncodeImage(0 + dt.Rows[0]["ProductNo"].ToString(), 15); QRCodepath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Image\\" + dt.Rows[0]["ProductNo"].ToString(); dataMatixCode.Save(QRCodepath); } else if (LorR == 1) { Bitmap dataMatixCode = dataMatix.EncodeImage(1 + dt.Rows[0]["ProductNo"].ToString(), 15); QRCodepath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Image\\" + dt.Rows[0]["ProductNo"].ToString(); dataMatixCode.Save(QRCodepath); } Microsoft.Office.Interop.Excel.Range m_objRange = worksheet.get_Range("B6", Type.Missing); m_objRange.Select(); Excel.Pictures pics = (Excel.Pictures)worksheet.Pictures(); pics.Insert(QRCodepath, m_objRange); Dictionary <int, string> DictPrinterName = new Dictionary <int, string>(); worksheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4; //纸张大小 //worksheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; 页面横向 worksheet.PageSetup.CenterHorizontally = true; //文字水平居中 xlApp.Visible = true; System.Windows.Forms.Application.DoEvents(); //开始打印 worksheet.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //打印预览 //worksheet.PrintPreview(); //打印结束后清除Excel内存 workbooks.Close(); xlApp.Application.Quit(); xlApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); GC.Collect();//强行销毁 } }
//----------------------------------------------------------// // Name : Print // // Description : Impression du fichier excel // // Arguments : // // Rédacteur : Scherrer Ludovic // //----------------------------------------------------------// void Print(string printer) { exWs.PrintOut(Type.Missing, Type.Missing, Type.Missing, false, printer, false, false, Type.Missing); }
private void Save(String ID, int count_row) { int count = 0; double sum = 0; loading.Visible = true; done.Visible = false; button4.Visible = false; button5.Visible = false; CloseExcel(); OpenExcel(); try { Excel.Range Line = (Excel.Range)myExcelWorksheet.Rows[10]; myExcelWorksheet.get_Range("G6", misValue).Formula = number.Text; myExcelWorksheet.get_Range("C5", misValue).Formula = hd_num.Text; myExcelWorksheet.get_Range("C6", misValue).Formula = date.Text + "/" + month.Text + "/" + year.Text; myExcelWorksheet.get_Range("G5", misValue).Formula = hd_date.Text + "/" + hd_month.Text + "/" + hd_year.Text; myExcelWorksheet.get_Range("C7", misValue).Formula = KH.Text; DataGridViewRow row; for (int i = 0; i < count_row - 1; i++) { row = dg_list.Rows[i]; if (row.Cells[0].Value != null) { count++; if (count < count_row - 2) { Line.Insert(); } String row_num = (8 + count).ToString(); double price = Double.Parse(row.Cells[1].Value.ToString()) * Double.Parse(row.Cells[2].Value.ToString()); sum += price; myExcelWorksheet.get_Range("A" + row_num, misValue).Formula = count; myExcelWorksheet.get_Range("B" + row_num, misValue).Formula = row.Cells[0].Value.ToString(); myExcelWorksheet.get_Range("D" + row_num, misValue).Formula = row.Cells[3].Value.ToString(); myExcelWorksheet.get_Range("E" + row_num, misValue).Formula = row.Cells[2].Value.ToString(); myExcelWorksheet.get_Range("F" + row_num, misValue).Formula = row.Cells[1].Value.ToString(); myExcelWorksheet.get_Range("G" + row_num, misValue).Formula = price; } } String num; double gtgt = sum / 10; // count = count + 4; num = (9 + count).ToString(); myExcelWorksheet.get_Range("G" + num, misValue).Formula = sum; count = count + 2; num = (9 + count).ToString(); myExcelWorksheet.get_Range("G" + num, misValue).Formula = gtgt; count = count + 1; num = (9 + count).ToString(); myExcelWorksheet.get_Range("G" + num, misValue).Formula = sum + gtgt; string path = Application.StartupPath + "\\ThongKe\\" + year.Text + "\\Thang" + month.Text; // your code goes here if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } myExcelWorkbook.SaveAs(path + "\\PTT-" + date.Text + "-" + month.Text + "-" + year.Text + "-" + number.Text + ".xls"); // myExcelWorkbook.Close(); String sql_delete = "DELETE FROM phieuthanhtoan WHERE ID='" + ID + "'"; using (OleDbCommand cmd = new OleDbCommand(sql_delete, conn)) { cmd.ExecuteNonQuery(); } count = 0; for (int i = 0; i < count_row - 1; i++) { row = dg_list.Rows[i]; if (row.Cells[0].Value != null) { String sql = "INSERT INTO phieuthanhtoan VALUES ('" + ID + "','" + year.Text + "','" + month.Text + "', '" + date.Text + "', '" + row.Cells[0].Value.ToString() + "', '" + row.Cells[2].Value.ToString() + "', '" + hd_date.Text + "', '" + hd_month.Text + "', '" + hd_year.Text + "', '" + hd_num.Text + "')"; using (OleDbCommand cmd = new OleDbCommand(sql, conn)) { cmd.ExecuteNonQuery(); } } count++; } foreach (DataGridViewRow r in dg_data.Rows) { thucDonTableAdapter.UpdateInventory(Double.Parse(r.Cells[3].Value.ToString()), r.Cells[0].Value.ToString()); } dataDataSet.AcceptChanges(); if (checkBox1.Checked) { try { myExcelWorksheet.PrintOut(1, 1, 1, false); } catch (Exception) { MessageBox.Show("Lỗi khi in"); } } loading.Visible = false; done.Visible = true; button4.Visible = true; button5.Visible = true; } catch (Exception) { MessageBox.Show("Có lỗi xảy ra"); } }
/// <summary> /// 打印. /// </summary> public void Print() { xlSheet.PrintOut(); }
/// <summary> /// Prints the current worksheet /// </summary> public void PrintWorksheet(int copies) { worksheet.PrintOut(missing, missing, copies, missing, true, missing, missing, missing); }
public void PrintOut() { xlSheet.PrintOut(xlMissing, xlMissing, xlMissing, xlMissing, xlMissing, xlMissing, xlMissing, xlMissing); }
private void tsbGrabar_Click(object sender, EventArgs e) { dgvOrdenVentaFormaPago_CellEndEdit(null, null); string mensaje = String.Empty; decimal total = Decimal.Parse(txtTotal.Text.Trim(), NumberStyles.Currency, Application.CurrentCulture); decimal cancelado = Decimal.Parse(txtCancelado.Text.Trim(), NumberStyles.Currency, Application.CurrentCulture); long numeroFactura = 0; long.TryParse(txtNumeroFactura.Text.Trim(), out numeroFactura); if (numeroFactura == 0) { mensaje += "Favor ingrese número de factura\n"; } if (numeroFactura > 0 && edmCosolemFunctions.existNumeroFactura(idEmpresa, idTienda, numeroFactura)) { mensaje += "Número de factura ya existe\n"; } if (cancelado < total) { mensaje += "Total de " + Util.FormatoMoneda((total - cancelado), 2) + " pendiente por cancelar\n"; } if (_BindingListtbOrdenVentaFormaPago.Where(x => x.idFormaPago == 0).Count() > 0) { mensaje += "Favor seleccionar forma de pago\n"; } if (_BindingListtbOrdenVentaFormaPago.Where(x => x.valor == 0).Count() > 0) { mensaje += "Favor ingrese valor\n"; } if (String.IsNullOrEmpty(mensaje.Trim())) { ordenVenta.idEstadoOrdenVenta = 5; ordenVenta.idEmpresaFactura = idEmpresa; ordenVenta.idTiendaFactura = idTienda; ordenVenta.numeroFactura = numeroFactura; ordenVenta.fechaHoraFactura = Program.fechaHora; ordenVenta.fechaHoraUltimaModificacion = Program.fechaHora; ordenVenta.idUsuarioUltimaModificacion = idUsuario; ordenVenta.terminalUltimaModificacion = Program.terminal; ordenVenta.tbOrdenVentaDetalle.Where(x => x.estadoRegistro).ToList().ForEach(y => { long idProducto = y.idProducto; if (edmCosolemFunctions.isProductoInventariable(idProducto)) { long idBodega = y.idBodega.Value; int cantidad = y.cantidad; bool estadoRegistro = y.estadoRegistro; tbInventario _tbInventario = (from I in _dbCosolemEntities.tbInventario where I.idBodega == idBodega && I.idProducto == idProducto && estadoRegistro select I).FirstOrDefault(); _tbInventario.fisicoDisponible -= cantidad; _tbInventario.reservado -= cantidad; _tbInventario.fechaHoraUltimaModificacion = Program.fechaHora; _tbInventario.idUsuarioUltimaModificacion = idUsuario; _tbInventario.terminalUltimaModificacion = Program.terminal; tbTransaccionInventario _tbTransaccionInventario = new tbTransaccionInventario(); _tbTransaccionInventario.tipoTransaccion = "Egreso de inventario por factura " + Util.setFormatoNumeroFactura(idEmpresa, idTienda, numeroFactura); _tbTransaccionInventario.idBodega = idBodega; _tbTransaccionInventario.idProducto = idProducto; _tbTransaccionInventario.cantidad = -cantidad; _tbTransaccionInventario.estadoRegistro = true; _tbTransaccionInventario.fechaHoraIngreso = Program.fechaHora; _tbTransaccionInventario.idUsuarioIngreso = idUsuario; _tbTransaccionInventario.terminalIngreso = Program.terminal; _dbCosolemEntities.tbTransaccionInventario.AddObject(_tbTransaccionInventario); } }); _BindingListtbOrdenVentaFormaPago.ToList().ForEach(x => ordenVenta.tbOrdenVentaFormaPago.Add(x)); _dbCosolemEntities.SaveChanges(); MessageBox.Show("Orden de venta facturada satisfactoriamente", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); Excel.Application application = new Excel.Application(); application.Visible = false; Excel.Workbook workbook = application.Workbooks.Open(Application.StartupPath + "\\Reportes\\FORMATO FACTURA.xlsx"); Excel.Worksheet worksheet = workbook.Worksheets["FORMATO"]; worksheet.Cells[5, 2].value = ordenVenta.cliente; worksheet.Cells[6, 2].value = ordenVenta.numeroIdentificacion; worksheet.Cells[7, 2].value = ordenVenta.direccion; worksheet.Cells[5, 10].value = ordenVenta.fechaHoraFactura.Value.ToString("dd/MM/yyyy"); worksheet.Cells[6, 10].value = String.Join(", ", new List <string> { ordenVenta.convencional, ordenVenta.celular }); int RowIndex = 11; ordenVenta.tbOrdenVentaDetalle.Where(x => x.estadoRegistro).ToList().ForEach(y => { decimal precio = (ordenVenta.idFormaPago == 1 ? y.precioOferta : y.precioVentaPublico); if (ordenVenta.tipoVenta == "P") { precio = y.precio; } worksheet.Cells[RowIndex, 1].value = y.cantidad; worksheet.Cells[RowIndex, 3].value = y.tbProducto.descripcion; worksheet.Cells[RowIndex, 9].value = precio; worksheet.Cells[RowIndex, 11].value = precio * y.cantidad; RowIndex += 1; }); worksheet.Cells[22, 3].value = ordenVenta.tbFormaPago.descripcion + (ordenVenta.idFormaPago == 1 ? "" : " - " + ordenVenta.tbProductoFinancieroCabecera.descripcion); worksheet.Cells[23, 11].value = ordenVenta.subTotalBruto; worksheet.Cells[24, 5].value = Util.ConvertirNumeroALetras(ordenVenta.totalNeto.ToString(), true, "dólares"); worksheet.Cells[24, 11].value = (ordenVenta.tipoVenta == "P" ? ordenVenta.descuento : 0M); worksheet.Cells[26, 11].value = ordenVenta.IVA; worksheet.Cells[27, 11].value = ordenVenta.totalNeto; worksheet.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); workbook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value); application.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(application); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); this.DialogResult = System.Windows.Forms.DialogResult.OK; } else { MessageBox.Show(mensaje, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void btnNyomtat_Click(object sender, EventArgs e) { try { Excel.Application excelApp = new Excel.Application(); // Munkafüzet megnyitása: Excel.Workbook wb = excelApp.Workbooks.Open( Application.StartupPath + @"\ossz.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); try { // Első munkaterület // (Excel uses base 1 indexing, not base 0.) Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1]; // Nyomtatás az alapért. nyomtatóra 1 példányban: ws.PrintOut( Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Tisztítás: GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(ws); wb.Close(false, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(wb); excelApp.Quit(); Marshal.FinalReleaseComObject(excelApp); } catch (Exception pex) { MessageBox.Show("Hiba " + pex.Message, "Hiba!"); } } catch (Exception ex) { MessageBox.Show("Hiba " + ex.Message, "Hiba!"); } /* CSV nyomtatása * try * { * // ossz.csv-ből kiolvassuk az adatokat * FileStream fs = new FileStream("ossz.csv", FileMode.Open); * streamToPrint = new StreamReader(fs, Encoding.UTF8); * try * { * printFont = new Font("Arial", 10); * PrintDocument pd = new PrintDocument(); * printDialog1.AllowSomePages = true; * printDialog1.ShowHelp = true; * printDialog1.Document = pd; * DialogResult result = printDialog1.ShowDialog(); * // OK gombra kattint * if (result == DialogResult.OK) * { * pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); * pd.Print(); * } * } * catch (Exception pex) * { * MessageBox.Show("Hiba " + pex.Message, "Hiba!"); * } * finally * { * streamToPrint.Close(); * fs.Close(); * } * } * catch (Exception ex) * { * MessageBox.Show("Hiba " + ex.Message, "Hiba!"); * } */ }
/// <summary> /// パートタイマー勤務票印刷 /// </summary> /// <param name="xlsPath">勤務票エクセルシートパス</param> /// <param name="dg1">データグリッドビューオブジェクト</param> private void sReportPart(string xlsPath, DataGridView dg1) { string sID = string.Empty; try { //マウスポインタを待機にする this.Cursor = Cursors.WaitCursor; Excel.Application oXls = new Excel.Application(); Excel.Workbook oXlsBook = (Excel.Workbook)(oXls.Workbooks.Open(xlsPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)); //Excel.Worksheet oxlsSheet = new Excel.Worksheet(); // スタッフIDによるシートの判断 Excel.Worksheet oxlsSheet = (Excel.Worksheet)oXlsBook.Sheets["ID1"]; sID = "1"; Excel.Range[] rng = new Microsoft.Office.Interop.Excel.Range[2]; // データベース接続 SysControl.SetDBConnect sDB = new SysControl.SetDBConnect(); OleDbCommand sCom = new OleDbCommand(); sCom.Connection = sDB.cnOpen(); OleDbDataReader dr = null; try { //グリッドを順番に読む for (int i = 0; i < dg1.RowCount; i++) { //チェックがあるものを対象とする if (dg1.Rows[i].Selected) { ////印刷2件目以降はシートを追加する //pCnt++; //if (pCnt > 1) //{ // oxlsSheet.Copy(Type.Missing, oXlsBook.Sheets[pCnt - 1]); // oxlsSheet = (Excel.Worksheet)oXlsBook.Sheets[pCnt]; //} // シートを初期化します oxlsSheet.Cells[3, 2] = string.Empty; oxlsSheet.Cells[3, 5] = string.Empty; oxlsSheet.Cells[3, 6] = string.Empty; oxlsSheet.Cells[3, 7] = string.Empty; oxlsSheet.Cells[3, 8] = string.Empty; oxlsSheet.Cells[3, 9] = string.Empty; oxlsSheet.Cells[3, 10] = string.Empty; oxlsSheet.Cells[3, 11] = string.Empty; oxlsSheet.Cells[3, 14] = string.Empty; oxlsSheet.Cells[3, 26] = string.Empty; oxlsSheet.Cells[3, 27] = string.Empty; oxlsSheet.Cells[3, 28] = string.Empty; oxlsSheet.Cells[3, 29] = string.Empty; oxlsSheet.Cells[3, 31] = string.Empty; oxlsSheet.Cells[3, 32] = string.Empty; oxlsSheet.Cells[4, 4] = string.Empty; oxlsSheet.Cells[4, 26] = string.Empty; oxlsSheet.Cells[5, 4] = string.Empty; oxlsSheet.Cells[5, 5] = string.Empty; oxlsSheet.Cells[5, 6] = string.Empty; oxlsSheet.Cells[5, 11] = string.Empty; for (int ix = 8; ix <= 38; ix++) { oxlsSheet.Cells[ix, 1] = string.Empty; oxlsSheet.Cells[ix, 2] = string.Empty; rng[0] = (Excel.Range)oxlsSheet.Cells[ix, 1]; rng[1] = (Excel.Range)oxlsSheet.Cells[ix, 2]; oxlsSheet.get_Range(rng[0], rng[1]).Interior.ColorIndex = Excel.XlColorIndex.xlColorIndexNone; } int sRow = i; // ID oxlsSheet.Cells[3, 2] = sID; // 個人番号 oxlsSheet.Cells[3, 5] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(0, 1); oxlsSheet.Cells[3, 6] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(1, 1); oxlsSheet.Cells[3, 7] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(2, 1); oxlsSheet.Cells[3, 8] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(3, 1); oxlsSheet.Cells[3, 9] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(4, 1); oxlsSheet.Cells[3, 10] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(5, 1); oxlsSheet.Cells[3, 11] = dg1[GridviewSet.col_ID, i].Value.ToString().Substring(6, 1); // 氏名 oxlsSheet.Cells[3, 14] = dg1[GridviewSet.col_Name, i].Value.ToString(); // 年 oxlsSheet.Cells[3, 26] = "2"; oxlsSheet.Cells[3, 27] = "0"; oxlsSheet.Cells[3, 28] = this.txtYear.Text.Substring(0, 1); oxlsSheet.Cells[3, 29] = this.txtYear.Text.Substring(1, 1); // 月 oxlsSheet.Cells[3, 31] = this.txtMonth.Text.Substring(0, 1); oxlsSheet.Cells[3, 32] = this.txtMonth.Text.Substring(1, 1); // 契約期間 oxlsSheet.Cells[4, 4] = dg1[GridviewSet.col_Keiyaku, i].Value.ToString(); // 就業時間 oxlsSheet.Cells[4, 26] = dg1[GridviewSet.col_WorkTime, i].Value.ToString(); // 勤務場所店番 oxlsSheet.Cells[5, 4] = dg1[GridviewSet.col_sID, i].Value.ToString().Substring(2, 1); oxlsSheet.Cells[5, 5] = dg1[GridviewSet.col_sID, i].Value.ToString().Substring(3, 1); oxlsSheet.Cells[5, 6] = dg1[GridviewSet.col_sID, i].Value.ToString().Substring(4, 1); // 勤務場所名称 oxlsSheet.Cells[5, 11] = dg1[GridviewSet.col_sName1, i].Value.ToString(); // 日・曜日 DateTime dt; string sDate = "20" + txtYear.Text + "/" + txtMonth.Text + "/"; for (int ix = 8; ix <= 38; ix++) { int days = ix - 7; if (DateTime.TryParse(sDate + days.ToString(), out dt)) { string youbi = ("日月火水木金土").Substring(int.Parse(dt.DayOfWeek.ToString("d")), 1); oxlsSheet.Cells[ix, 1] = days.ToString(); oxlsSheet.Cells[ix, 2] = youbi; rng[0] = (Excel.Range)oxlsSheet.Cells[ix, 1]; // 土日の場合 if (youbi == "日" || youbi == "土") { oxlsSheet.get_Range(rng[0], rng[0]).Interior.ColorIndex = 15; } else { // 休日テーブルを参照し休日に該当するか調べます sCom.CommandText = "select * from 休日 where 年=? and 月=? and 日=?"; sCom.Parameters.Clear(); sCom.Parameters.AddWithValue("@year", int.Parse("20" + txtYear.Text)); sCom.Parameters.AddWithValue("@Month", int.Parse(txtMonth.Text)); sCom.Parameters.AddWithValue("@day", days); dr = sCom.ExecuteReader(); if (dr.HasRows) { oxlsSheet.get_Range(rng[0], rng[0]).Interior.ColorIndex = 15; } dr.Close(); } } } // ウィンドウを非表示にする //oXls.Visible = false; //印刷 //oxlsSheet.PrintPreview(false); oxlsSheet.PrintOut(1, Type.Missing, 1, false, oXls.ActivePrinter, Type.Missing, Type.Missing, Type.Missing); //oXlsBook.PrintOut(); } } // マウスポインタを元に戻す this.Cursor = Cursors.Default; // 終了メッセージ MessageBox.Show("印刷が終了しました", "勤務票印刷", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { MessageBox.Show(e.Message, "印刷処理", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { // ウィンドウを非表示にする oXls.Visible = false; // 保存処理 oXls.DisplayAlerts = false; // Bookをクローズ oXlsBook.Close(Type.Missing, Type.Missing, Type.Missing); // Excelを終了 oXls.Quit(); // COMオブジェクトの参照カウントを解放する System.Runtime.InteropServices.Marshal.ReleaseComObject(oxlsSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(oXlsBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(oXls); // マウスポインタを元に戻す this.Cursor = Cursors.Default; // データリーダーを閉じる if (dr.IsClosed == false) { dr.Close(); } // データベースを切断 if (sCom.Connection.State == ConnectionState.Open) { sCom.Connection.Close(); } } } catch (Exception e) { MessageBox.Show(e.Message, "印刷処理", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } // マウスポインタを元に戻す this.Cursor = Cursors.Default; }
/// <summary> /// 按索引查找sheet,使用默认pdf打印机转换为pdf /// </summary> /// <param name="fromExcelPath">源excel路径</param> /// <param name="worksheetIndex">sheet索引,注意从1开始</param> /// <returns>成功或失败</returns> public bool ConvertExcelWorkSheetPDF_index(string fromExcelPath, int worksheetIndex) { bool flag = true; try { if (fromExcelPath.Length == 0) { flag = false; throw new Exception("需要转换的源文件路径不能为空。"); } Microsoft.Office.Interop.Excel.ApplicationClass applicationClass = new Microsoft.Office.Interop.Excel.ApplicationClass(); applicationClass.GetType(); Workbooks workbooks = applicationClass.Workbooks;//.get_Workbooks(); Type type = workbooks.GetType(); object obj = fromExcelPath; object[] objArray = new object[] { obj, true, true }; Microsoft.Office.Interop.Excel.Workbook workbook = (Microsoft.Office.Interop.Excel.Workbook)type.InvokeMember("Open", BindingFlags.InvokeMethod, null, workbooks, objArray); //workbooks.Open(this._sourcePath); //Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Item[0]; workbook.GetType(); //object obj1 = "c:\\temp.ps"; //obj1 = toPdfPath; object obj2 = "-4142"; //Microsoft.Office.Interop.Excel.Worksheet item = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Item[worksheetIndex]; Microsoft.Office.Interop.Excel.Worksheet item = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(worksheetIndex); if (item == null) { flag = false; throw new Exception("需要转换的WorkSheet名称不存在。"); } //item.get_Cells().get_Interior().set_ColorIndex(obj2); item.Cells.Interior.ColorIndex = obj2;//.get_Interior().set_ColorIndex(obj2); object value = Missing.Value; //item.PrintOut(value, value, value, value, value, true, value, obj1); //Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; //item.ExportAsFixedFormat(targetType, obj1, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard,true,false, value, value, value, value); //目标路径仅在打印失败时写入,成功时都默认在打印机路径下 //故不使用目标路径,直接使用打印机默认路径 item.PrintOut(value, value, value, value, value, false, value, value); if (item != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(item); //Marshal.FinalReleaseComObject(sheet); item = null; } if (workbook != null) { workbook.Close(false, Type.Missing, Type.Missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); //Marshal.FinalReleaseComObject(workBook); workbook = null; } if (workbooks != null) { workbooks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks); workbooks = null; } if (applicationClass != null) { applicationClass.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(applicationClass); applicationClass = null; } GC.Collect(); GC.WaitForPendingFinalizers(); return(flag); } catch (Exception exception) { classLims_NPOI.WriteLog(exception, ""); throw exception; } finally { } }