Thứ Tư, 22 tháng 4, 2015

Tạo file excel và xuất ra máy in

MemoryStream ms = new MemoryStream();
Workbook workbook = new Workbook(@"TenFile.xlsx");

void TaoFileVaIn(bool xuatBan)
{
      // Lấy sheet mẫu
      Worksheet worksheet = workbook.Worksheets[0];
      worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
      worksheet.PageSetup.Orientation = PageOrientationType.Landscape;
      // Chuyển worksheet mẫu về đầu
      worksheet.Move(0);
      // Chỉ định sheet đang hoạt động là sheet đầu tiên
      workbook.Worksheets.ActiveSheetIndex = 0;
      // Không hiển thị đầy đủ lưới
      // worksheet.IsGridlinesVisible = false;
      int stt = 1;
      int sohang = 17;

      string now = "Tháng " + cbbThang.Text + " năm " + cbbNam.Text;
      worksheet.Cells["A8"].Value = now;

      for (int i = 0; i < listBKTH01.Count; i++)
      {
          worksheet.Cells.InsertRow(17);
      }
      //Style cellA = worksheet.Cells["A16"].GetStyle();

      for (int i = 0; i < listBKTH01.Count ;i++ )
      {
          worksheet.Cells["A" + sohang].Value = stt;
          worksheet.Cells["B" + sohang].Value = "GiaTri";
          stt++;
          sohang++;
      }
      worksheet.Cells["C" + sohang].Formula = "=SUM(C17:C" + (sohang - 1) + ")";

      if (xuatBan)
      {
          try
          {
               Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();
               options.PrintingPage = PrintingPageType.Default;
               worksheet.PageSetup.FitToPagesTall = 1;

               //Setting the number of pages to which the width of the worksheet will be spanned
               worksheet.PageSetup.FitToPagesWide = 1;

              //Setting the paper size to A4
              worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
              SheetRender sr = new SheetRender(worksheet, options);
                        sr.ToPrinter(Properties.Settings.Default.TenMayIn);
     }
     catch
     {
              ThongBao.BaoLoi("Không tìm thấy máy in đã chỉ định!");
                }
      }
            // Truyền dữ liệu vào luồng excel để hiển thị trên form excel
            else
            {
                workbook.Save(ms, SaveFormat.Xlsx);
            }
        }

private void btnXemDuLieu_Click(object sender, EventArgs e)
{
            TaoFileVaIn(false);
            frmXemTruoc f = new frmXemTruoc(ms);
            f.Show();
}

Không có nhận xét nào:

Đăng nhận xét