⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 csvexportdialog.java

📁 Java的Web报表库
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.NONE;
    gbc.weightx = 0;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(1, 1, 1, 1);
    otherPanel.add(rbSeparatorOther, gbc);

    gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1;
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.insets = new Insets(1, 1, 1, 1);
    otherPanel.add(txSeparatorOther, gbc);

    gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1;
    gbc.gridx = 0;
    gbc.gridy = 3;
    gbc.gridwidth = 3;
    gbc.insets = new Insets(1, 1, 1, 1);
    separatorPanel.add(otherPanel, gbc);

    return separatorPanel;
  }

  /**
   * Returns the export file name.
   *
   * @return The file name.
   */
  public String getFilename()
  {
    return txFilename.getText();
  }

  /**
   * Sets the export file name.
   *
   * @param filename  the file name.
   */
  public void setFilename(final String filename)
  {
    this.txFilename.setText(filename);
  }

  /**
   * Returns <code>true</code> if the user confirmed the selection, and <code>false</code>
   * otherwise.  The file should only be saved if the result is <code>true</code>.
   *
   * @return  A boolean.
   */
  public boolean isConfirmed()
  {
    return confirmed;
  }

  /**
   * Defines whether this dialog has been finished using the 'OK' or the 'Cancel' option.
   *
   * @param confirmed set to <code>true</code>, if OK was pressed, <code>false</code> otherwise
   */
  protected void setConfirmed(final boolean confirmed)
  {
    this.confirmed = confirmed;
  }

  /**
   * Clears all selections, input fields and sets the selected encryption level to none.
   */
  public void clear()
  {
    txFilename.setText("");
    cbEncoding.setSelectedIndex(
        encodingModel.indexOf(System.getProperty("file.encoding", "Cp1251")));
    rbExportPrintedElements.setSelected(true);
    rbSeparatorColon.setSelected(true);
    cbxStrictLayout.setSelected(false);
    performSeparatorSelection();
  }

  /**
   * Returns the separator string, which is controlled by the selection of radio buttons.
   *
   * @return The separator string.
   */
  public String getSeparatorString()
  {
    if (rbSeparatorColon.isSelected())
    {
      return ",";
    }
    if (rbSeparatorSemicolon.isSelected())
    {
      return ";";
    }
    if (rbSeparatorTab.isSelected())
    {
      return "\t";
    }
    if (rbSeparatorOther.isSelected())
    {
      return txSeparatorOther.getText();
    }
    return "";
  }

  /**
   * Sets the separator string.
   *
   * @param s  the separator.
   */
  public void setSeparatorString(final String s)
  {
    if (s == null)
    {
      rbSeparatorOther.setSelected(true);
      txSeparatorOther.setText("");
    }
    else if (s.equals(","))
    {
      rbSeparatorColon.setSelected(true);
    }
    else if (s.equals(";"))
    {
      rbSeparatorSemicolon.setSelected(true);
    }
    else if (s.equals("\t"))
    {
      rbSeparatorTab.setSelected(true);
    }
    else
    {
      rbSeparatorOther.setSelected(true);
      txSeparatorOther.setText(s);
    }
    performSeparatorSelection();
  }

  /**
   * Returns the encoding.
   *
   * @return The encoding.
   */
  public String getEncoding()
  {
    if (cbEncoding.getSelectedIndex() == -1)
    {
      return System.getProperty("file.encoding");
    }
    else
    {
      return encodingModel.getEncoding(cbEncoding.getSelectedIndex());
    }
  }

  /**
   * Sets the encoding.
   *
   * @param encoding  the encoding.
   */
  public void setEncoding(final String encoding)
  {
    cbEncoding.setSelectedIndex(encodingModel.indexOf(encoding));
  }

  /**
   * Returns <code>true</code> if the user selected to export raw data only, and <code>false</code>
   * otherwise.
   *
   * @return A boolean.
   */
  public boolean isExportRawData()
  {
    return rbExportData.isSelected();
  }

  /**
   * Sets a flag that controls whether raw data is exported.
   *
   * @param b  the new flag value.
   */
  public void setExportRawData(final boolean b)
  {
    if (b == true)
    {
      rbExportData.setSelected(true);
    }
    else
    {
      rbExportPrintedElements.setSelected(true);
    }
  }

  /**
   * Selects a file to use as target for the report processing.
   */
  protected void performSelectFile()
  {
    if (fileChooser == null)
    {
      fileChooser = new JFileChooser();
      fileChooser.addChoosableFileFilter(
          new ExtensionFileFilter("Comma Separated Value files", ".csv"));
      fileChooser.setMultiSelectionEnabled(false);
    }

    fileChooser.setSelectedFile(new File(getFilename()));
    final int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION)
    {
      final File selFile = fileChooser.getSelectedFile();
      String selFileName = selFile.getAbsolutePath();

      // Test if ends on csv
      if (StringUtil.endsWithIgnoreCase(selFileName, ".csv") == false)
      {
        selFileName = selFileName + ".csv";
      }
      setFilename(selFileName);
    }
  }

  /**
   * Validates the contents of the dialog's input fields. If the selected file exists, it is also
   * checked for validity.
   *
   * @return <code>true</code> if the input is valid, <code>false</code> otherwise
   */
  public boolean performValidate()
  {
    final String filename = getFilename();
    if (filename.trim().length() == 0)
    {
      JOptionPane.showMessageDialog(this,
          getResources().getString("csvexportdialog.targetIsEmpty"),
          getResources().getString("csvexportdialog.errorTitle"),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    final File f = new File(filename);
    if (f.exists())
    {
      if (f.isFile() == false)
      {
        JOptionPane.showMessageDialog(this,
            getResources().getString("csvexportdialog.targetIsNoFile"),
            getResources().getString("csvexportdialog.errorTitle"),
            JOptionPane.ERROR_MESSAGE);
        return false;
      }
      if (f.canWrite() == false)
      {
        JOptionPane.showMessageDialog(this,
            getResources().getString(
                "csvexportdialog.targetIsNotWritable"),
            getResources().getString("csvexportdialog.errorTitle"),
            JOptionPane.ERROR_MESSAGE);
        return false;
      }
      final String key1 = "csvexportdialog.targetOverwriteConfirmation";
      final String key2 = "csvexportdialog.targetOverwriteTitle";
      if (JOptionPane.showConfirmDialog(this,
          MessageFormat.format(getResources().getString(key1),
              new Object[]{getFilename()}
          ),
          getResources().getString(key2),
          JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
          == JOptionPane.NO_OPTION)
      {
        return false;
      }
    }

    return true;
  }

  /**
   * Shows this dialog and (if the dialog is confirmed) saves the complete report into a CSV file.
   *
   * @param report  the report being processed.
   *
   * @return true or false.
   * @deprecated this dialog should only be used to configure the export process
   */
  public boolean performExport(final JFreeReport report)
  {
    initFromConfiguration(report.getReportConfiguration());
    setModal(true);
    setVisible(true);
    if (isConfirmed() == false)
    {
      return true;
    }
    if (isExportRawData())
    {
      return writeRawCSV(report);
    }
    else
    {
      return writeLayoutedCSV(report);
    }
  }

  public boolean performQueryForExport (final JFreeReport report)
  {
    setModal(true);
    initFromConfiguration(report.getReportConfiguration());
    setVisible(true);
    if (isConfirmed() == false)
    {
      return false;
    }
    storeToConfiguration(report.getReportConfiguration());
    return true;
  }

  /**
   * Saves a report to CSV format.
   *
   * @param report  the report.
   *
   * @return true or false.
   * @deprecated this dialog should only be used to configure the export process
   */
  public boolean writeLayoutedCSV(final JFreeReport report)
  {
    Writer out = null;
    try
    {

      out = new BufferedWriter(
          new OutputStreamWriter(
              new FileOutputStream(
                  new File(getFilename())), getEncoding()));
      final CSVTableProcessor target = new CSVTableProcessor(report, getSeparatorString());
      target.setWriter(out);
      target.setStrictLayout(isStrictLayout());
      target.processReport();
      return true;
    }
    catch (Exception re)
    {
      showExceptionDialog("error.processingfailed", re);
      return false;
    }
    finally
    {
      try
      {
        if (out != null)
        {
          out.close();
        }
      }
      catch (Exception e)
      {
        showExceptionDialog("error.savefailed", e);
      }
    }
  }

  /**
   * Saves a report to CSV format.
   *
   * @param report  the report.
   *
   * @return true or false.
   */
  public boolean writeRawCSV(final JFreeReport report)
  {
    Writer out = null;
    try
    {

      out = new BufferedWriter(
          new OutputStreamWriter(
              new FileOutputStream(
                  new File(getFilename())), getEncoding()));
      final CSVProcessor target = new CSVProcessor(report, getSeparatorString());
      target.setWriter(out);
      target.processReport();
      out.close();
      return true;
    }
    catch (Exception re)
    {
      showExceptionDialog("error.processingfailed", re);
      return false;
    }
    finally
    {
      try
      {
        if (out != null)
        {
          out.close();
        }
      }
      catch (Exception e)
      {
        showExceptionDialog("error.savefailed", e);
      }
    }
  }

  /**
   * Shows the exception dialog by using localized messages. The message base is
   * used to construct the localisation key by appending ".title" and ".message" to the
   * base name.
   *
   * @param localisationBase  the resource key prefix.
   * @param e  the exception.
   */
  private void showExceptionDialog(final String localisationBase, final Exception e)
  {
    ExceptionDialog.showExceptionDialog(
        getResources().getString(localisationBase + ".title"),
        MessageFormat.format(
            getResources().getString(localisationBase + ".message"),
            new Object[]{e.getLocalizedMessage()}
        ),
        e);
  }

  /**
   * Initialises the CSV export dialog from the settings in the report configuration.
   *
   * @param config  the report configuration.
   */
  public void initFromConfiguration(final ReportConfiguration config)
  {
    setSeparatorString(config.getConfigProperty(CSVProcessor.CSV_SEPARATOR, ","));

    String strict = config.getConfigProperty
        (CSVTableProcessor.CONFIGURATION_PREFIX +
          CSVTableProcessor.STRICT_LAYOUT,
            config.getConfigProperty (ReportConfiguration.STRICT_TABLE_LAYOUT,
                ReportConfiguration.STRICT_TABLE_LAYOUT_DEFAULT));
    setStrictLayout(strict.equals("true"));
    String encoding = config.getCSVTargetEncoding ();
    encodingModel.ensureEncodingAvailable(encoding);
    setEncoding(encoding);
  }

  public void storeToConfiguration (final ReportConfiguration config)
  {
    config.setConfigProperty(CSVProcessor.CSV_SEPARATOR, getSeparatorString());
    config.setConfigProperty(CSVTableProcessor.CONFIGURATION_PREFIX +
        CSVTableProcessor.SEPARATOR_KEY, getSeparatorString());
    config.setConfigProperty(CSVTableProcessor.STRICT_LAYOUT, String.valueOf(isStrictLayout()));
  }

  /**
   * Enables or disables the 'other' separator text field.
   */
  protected void performSeparatorSelection()
  {
    if (rbSeparatorOther.isSelected())
    {
      txSeparatorOther.setEnabled(true);
    }
    else
    {
      txSeparatorOther.setEnabled(false);
    }
  }

  /**
   * Returns the current setting of the 'strict layout' combo-box.
   *
   * @return A boolean.
   */
  public boolean isStrictLayout()
  {
    return cbxStrictLayout.isSelected();
  }

  /**
   * Sets the 'strict layout' combo-box setting.
   *
   * @param strictLayout  the new setting.
   */
  public void setStrictLayout(final boolean strictLayout)
  {
    cbxStrictLayout.setSelected(strictLayout);
  }

  /**
   * This method exists for debugging purposes.
   *
   * @param args  ignored.
   */
  public static void main(final String[] args)
  {
    final JDialog d = new CSVExportDialog();
    d.pack();
    d.addWindowListener(new WindowAdapter()
    {
      /**
       * Invoked when a window is in the process of being closed.
       * The close operation can be overridden at this point.
       */
      public void windowClosing(final WindowEvent e)
      {
        System.exit(0);
      }
    });
    d.setVisible(true);
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -