سؤال

يمكن لأي شخص أن يوصي API بسيطة من شأنها أن تسمح لي أن استخدام قراءة CSV ملف الإدخال ، والقيام ببعض بسيطة التحولات ، ثم اكتبها.

سريع جوجل وجدت http://flatpack.sourceforge.net/ والتي تبدو واعدة.

أردت فقط أن تحقق الآخرين ما تستخدم قبل عدة نفسي هذا API.

هل كانت مفيدة؟

المحلول

أباتشي العموم CSV

تحقق من أباتشي المشتركة CSV.

هذه المكتبة يقرأ ويكتب العديد من الاختلافات من CSV, بما في ذلك معيار واحد RFC 4180.كما يقرأ/يكتب المفصول ملفات.

  • Excel
  • InformixUnload
  • InformixUnloadCsv
  • الخلية
  • أوراكل
  • PostgreSQLCsv
  • PostgreSQLText
  • RFC4180
  • TDF

نصائح أخرى

لقد استعملت OpenCSV في الماضي.

import au.com.bytecode.opencsv.CSVReader;

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));

// إذا كان السطر الأول هو رأس String[] header = القارئ.readNext();
// تكرار أكثر من قارئ.readNext حتى تعود فارغة String[] خط = القارئ.readNext();

كانت هناك بعض الخيارات الأخرى في الإجابات سؤال آخر.

تحديث: التعليمات البرمجية في هذا الجواب هو السوبر CSV 1.52.تحديث أمثلة التعليمات البرمجية ل سوبر CSV 2.4.0 يمكن العثور عليها في موقع المشروع على الإنترنت:http://super-csv.github.io/super-csv/index.html


على SuperCSV المشروع مباشرة تدعم تحليل منظم التلاعب CSV الخلايا.من http://super-csv.github.io/super-csv/examples_reading.html ستجد مثلا

بالنظر إلى فئة

public class UserBean {
    String username, password, street, town;
    int zip;

    public String getPassword() { return password; }
    public String getStreet() { return street; }
    public String getTown() { return town; }
    public String getUsername() { return username; }
    public int getZip() { return zip; }
    public void setPassword(String password) { this.password = password; }
    public void setStreet(String street) { this.street = street; }
    public void setTown(String town) { this.town = town; }
    public void setUsername(String username) { this.username = username; }
    public void setZip(int zip) { this.zip = zip; }
}

وأن يكون لديك ملف CSV مع رأس.دعونا نفترض المحتوى التالي

username, password,   date,        zip,  town
Klaus,    qwexyKiks,  17/1/2007,   1111, New York
Oufu,     bobilop,    10/10/2007,  4555, New York

ثم يمكنك إنشاء مثيل UserBean وملء مع القيم من السطر الثاني من ملف التعليمات البرمجية التالية

class ReadingObjects {
  public static void main(String[] args) throws Exception{
    ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
    try {
      final String[] header = inFile.getCSVHeader(true);
      UserBean user;
      while( (user = inFile.read(UserBean.class, header, processors)) != null) {
        System.out.println(user.getZip());
      }
    } finally {
      inFile.close();
    }
  }
}

باستخدام ما يلي "التلاعب في المواصفات"

final CellProcessor[] processors = new CellProcessor[] {
    new Unique(new StrMinMax(5, 20)),
    new StrMinMax(8, 35),
    new ParseDate("dd/MM/yyyy"),
    new Optional(new ParseInt()),
    null
};

القراءة تنسيق CSV الوصف يجعلني أشعر أن استخدام مكتبة 3rd الطرف سيكون أقل الصداع من الكتابة بنفسي:

ويكيبيديا قوائم 10 أو شيء من المكتبات المعروفة:

قارنت يبس المدرجة باستخدام نوع من قائمة الاختيار. OpenCSV تحولت الفائز لي (YMMV) النتائج التالية:

+ maven

+ maven - release version   // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side

+ code examples

+ open source   // as in "can hack myself if needed"

+ understandable javadoc   // as opposed to eg javadocs of _genjava gj-csv_

+ compact API   // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)

- reference to specification used   // I really like it when people can explain what they're doing

- reference to _RFC 4180_ support   // would qualify as simplest form of specification to me

- releases changelog   // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin   // _flatpack_, for comparison, has quite helpful changelog

+ bug tracking

+ active   // as in "can submit a bug and expect a fixed release soon"

+ positive feedback   // Recommended By 51 users at sourceforge (as of now)

نستخدم JavaCSV, أنه يعمل بشكل جيد جدا

آخر تطبيق المؤسسة عملت على أن هناك حاجة إلى التعامل مع ملحوظة كمية CSV -- بضعة أشهر -- كنت SuperCSV في سورس وجدت أنها بسيطة وقوية خالية من المشاكل.

يمكنك استخدام csvreader api & تحميل من الموقع التالي:

http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download

أو

http://sourceforge.net/projects/javacsv/

استخدام التعليمات البرمجية التالية:

/ ************ For Reading ***************/

import java.io.FileNotFoundException;
import java.io.IOException;

import com.csvreader.CsvReader;

public class CsvReaderExample {

    public static void main(String[] args) {
        try {

            CsvReader products = new CsvReader("products.csv");

            products.readHeaders();

            while (products.readRecord())
            {
                String productID = products.get("ProductID");
                String productName = products.get("ProductName");
                String supplierID = products.get("SupplierID");
                String categoryID = products.get("CategoryID");
                String quantityPerUnit = products.get("QuantityPerUnit");
                String unitPrice = products.get("UnitPrice");
                String unitsInStock = products.get("UnitsInStock");
                String unitsOnOrder = products.get("UnitsOnOrder");
                String reorderLevel = products.get("ReorderLevel");
                String discontinued = products.get("Discontinued");

                // perform program logic here
                System.out.println(productID + ":" + productName);
            }

            products.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

كتابة / إلحاقي إلى ملف CSV

كود:

/************* For Writing ***************************/

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.csvreader.CsvWriter;

public class CsvWriterAppendExample {

    public static void main(String[] args) {

        String outputFile = "users.csv";

        // before we open the file check to see if it already exists
        boolean alreadyExists = new File(outputFile).exists();

        try {
            // use FileWriter constructor that specifies open for appending
            CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

            // if the file didn't already exist then we need to write out the header line
            if (!alreadyExists)
            {
                csvOutput.write("id");
                csvOutput.write("name");
                csvOutput.endRecord();
            }
            // else assume that the file already has the correct header line

            // write out a few records
            csvOutput.write("1");
            csvOutput.write("Bruce");
            csvOutput.endRecord();

            csvOutput.write("2");
            csvOutput.write("John");
            csvOutput.endRecord();

            csvOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

هناك أيضا CSV/اكسل فائدة.فإنه يفترض كل thos بيانات الجدول مثل ويسلم البيانات من التكرار.

تنسيق CSV يبدو من السهل بما فيه الكفاية بالنسبة StringTokenizer ولكن يمكن أن تصبح أكثر تعقيدا.هنا في ألمانيا منقوطة يتم استخدام محدد و الخلايا التي تحتوي على المحددات بحاجة إلى أن هرب.أنت لا تنوي التعامل بسهولة مع StringTokenizer.

وأود أن تذهب http://sourceforge.net/projects/javacsv

إذا كنت تنوي قراءة csv من excel ، ثم هناك بعض الحالات الزاوية.لا أستطيع تذكر كل منهم ، ولكن أباتشي العموم csv لم تكن قادرة على التعامل مع ذلك بشكل صحيح (مثلا عناوين).

تأكد من اختبار excel الإخراج مع اقتباسات و الفواصل و مائلة في كل مكان.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top