其一:CSV文件读取与生成
①CSV文件读取
读取操作类:
- public class CSVReader {
- private BufferedReader br;
-
- private boolean hasNext = true;
-
- private char separator;
-
- private char quotechar;
-
- private int skipLines;
-
- private boolean linesSkiped;
-
-
- public static final char DEFAULT_SEPARATOR = ',';
-
-
-
-
-
- public static final char DEFAULT_QUOTE_CHARACTER = '"';
-
-
-
-
- public static final int DEFAULT_SKIP_LINES = 0;
-
-
-
-
-
-
-
- public CSVReader(Reader reader) {
- this(reader, DEFAULT_SEPARATOR);
- }
-
-
-
-
-
-
-
-
-
- public CSVReader(Reader reader, char separator) {
- this(reader, separator, DEFAULT_QUOTE_CHARACTER);
- }
-
-
-
-
-
-
-
-
-
-
-
- public CSVReader(Reader reader, char separator, char quotechar) {
- this(reader, separator, quotechar, DEFAULT_SKIP_LINES);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public CSVReader(Reader reader, char separator, char quotechar, int line) {
- this.br = new BufferedReader(reader);
- this.separator = separator;
- this.quotechar = quotechar;
- this.skipLines = line;
- }
-
-
-
-
-
-
-
-
-
-
-
- public List readAll() throws IOException {
-
- List allElements = new ArrayList();
- while (hasNext) {
- String[] nextLineAsTokens = readNext();
- if (nextLineAsTokens != null)
- allElements.add(nextLineAsTokens);
- }
- return allElements;
-
- }
-
-
-
-
-
-
-
-
-
-
- public String[] readNext() throws IOException {
-
- String nextLine = getNextLine();
- return hasNext ? parseLine(nextLine) : null;
- }
-
-
-
-
-
-
-
-
- private String getNextLine() throws IOException {
- if (!this.linesSkiped) {
- for (int i = 0; i < skipLines; i++) {
- br.readLine();
- }
- this.linesSkiped = true;
- }
- String nextLine = br.readLine();
- if (nextLine == null) {
- hasNext = false;
- }
- return hasNext ? nextLine : null;
- }
-
-
-
-
-
-
-
-
-
-
- private String[] parseLine(String nextLine) throws IOException {
-
- if (nextLine == null) {
- return null;
- }
-
- List tokensOnThisLine = new ArrayList();
- StringBuffer sb = new StringBuffer();
- boolean inQuotes = false;
- do {
- if (inQuotes) {
-
- sb.append("\n");
- nextLine = getNextLine();
- if (nextLine == null)
- break;
- }
- for (int i = 0; i < nextLine.length(); i++) {
-
- char c = nextLine.charAt(i);
- if (c == quotechar) {
-
-
-
- if (inQuotes
-
- && nextLine.length() > (i + 1)
-
-
- && nextLine.charAt(i + 1) == quotechar) {
-
-
-
-
-
-
-
-
-
- sb.append(nextLine.charAt(i + 1));
- i++;
- } else {
- inQuotes = !inQuotes;
-
-
- if (i > 2
- && nextLine.charAt(i - 1) != this.separator
-
-
-
-
-
-
-
- && nextLine.length() > (i + 1)
- && nextLine.charAt(i + 1) != this.separator
-
-
-
-
-
-
-
- ) {
- sb.append(c);
- }
- }
- } else if (c == separator && !inQuotes) {
- tokensOnThisLine.add(sb.toString());
- sb = new StringBuffer();
- } else {
- sb.append(c);
- }
- }
- } while (inQuotes);
- tokensOnThisLine.add(sb.toString());
- return (String[]) tokensOnThisLine.toArray(new String[0]);
-
- }
-
-
-
-
-
-
-
- public void close() throws IOException {
- br.close();
- }
-
- }
读取测试类
- public class CSVReaderTest {
- CSVReader csvr;
-
-
-
-
- @Before
- public void init() throws Exception {
- StringBuffer sb = new StringBuffer();
- sb.append("a,b,c").append("\n");
- sb.append("a,\"b,b,b\",c").append("\n");
- sb.append(",,").append("\n");
- sb.append("a,\"PO Box 123,\nKippax,ACT. 2615.\nAustralia\",d.\n");
- sb.append("\"Glen \"\"The Man\"\" Smith\",Athlete,Developer\n");
-
-
-
- sb.append("\"\"\"\"\"\",\"test\"\n");
-
- sb.append("\"a\nb\",b,\"\nd\",e\n");
- csvr = new CSVReader(new FileReader("d:/myfile.csv"));
-
-
- }
-
- @Test
- public void test1() throws IOException{
-
- CSVReader c = new CSVReader(new FileReader("d:/myfile.csv"), ',',
- '\"', 1);
- String[] nextline=c.readNext();
- System.out.println(nextline[0]);
- assertEquals("CRM4005", nextline[0]);
- }
-
-
-
-
-
-
-
-
- public void ParseLine() throws IOException {
-
-
- String[] nextLine = csvr.readNext();
- assertEquals("a", nextLine[0]);
- assertEquals("b", nextLine[1]);
- assertEquals("c", nextLine[2]);
-
-
- nextLine = csvr.readNext();
- assertEquals("a", nextLine[0]);
- assertEquals("b,b,b", nextLine[1]);
- assertEquals("c", nextLine[2]);
-
-
- nextLine = csvr.readNext();
- assertEquals(3, nextLine.length);
-
-
- nextLine = csvr.readNext();
- assertEquals(3, nextLine.length);
-
-
- nextLine = csvr.readNext();
- assertEquals("Glen \"The Man\" Smith", nextLine[0]);
-
- nextLine = csvr.readNext();
- assertTrue(nextLine[0].equals("\"\""));
- assertTrue(nextLine[1].equals("test"));
-
-
- nextLine = csvr.readNext();
- assertEquals(4, nextLine.length);
-
-
- assertEquals(null, csvr.readNext());
-
- }
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
-
- public void testParseAll() throws IOException {
-
- List allElements = csvr.readAll();
- assertEquals(7, allElements.size());
-
- }
-
-
-
-
-
-
-
-
- public void testOptionalConstructors() throws IOException {
-
- StringBuffer sb = new StringBuffer();
- sb.append("a\tb\tc").append("\n");
- sb.append("a\t'b\tb\tb'\tc").append("\n");
- CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t', '\'');
-
- String[] nextLine = c.readNext();
- assertEquals(3, nextLine.length);
-
- nextLine = c.readNext();
- assertEquals(3, nextLine.length);
-
- }
-
-
-
-
-
-
-
-
- public void testSkippingLines() throws IOException {
-
- StringBuffer sb = new StringBuffer();
- sb.append("Skip this line\t with tab").append("\n");
- sb.append("And this line too").append("\n");
- sb.append("a\t'b\tb\tb'\tc").append("\n");
- CSVReader c = new CSVReader(new StringReader(sb.toString()), '\t',
- '\'', 2);
-
- String[] nextLine = c.readNext();
- assertEquals(3, nextLine.length);
-
- assertEquals("a", nextLine[0]);
- }
-
-
-
-
-
-
-
-
- public void testParsedLineWithInternalQuota() throws IOException {
-
- StringBuffer sb = new StringBuffer();
-
- sb.append("a,123\"4\"567,c").append("\n");
-
- CSVReader c = new CSVReader(new StringReader(sb.toString()));
-
- String[] nextLine = c.readNext();
- assertEquals(3, nextLine.length);
-
- System.out.println(nextLine[1]);
- assertEquals("123\"4\"567", nextLine[1]);
-
- }
-
-
-
-
-
-
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(CSVReaderTest.class);
- }
-
- }
②CSV文件写入
文件写入操作类
- public class CSVWriter {
- private Writer rawWriter;
-
- private PrintWriter pw;
-
- private char separator;
-
- private char quotechar;
-
- private char escapechar;
-
- private String lineEnd;
-
-
- public static final char DEFAULT_ESCAPE_CHARACTER = '"';
-
-
- public static final char DEFAULT_SEPARATOR = ',';
-
-
-
-
-
- public static final char DEFAULT_QUOTE_CHARACTER = '"';
-
-
- public static final char NO_QUOTE_CHARACTER = '\u0000';
-
-
- public static final char NO_ESCAPE_CHARACTER = '\u0000';
-
-
- public static final String DEFAULT_LINE_END = "\n";
-
- private static final SimpleDateFormat TIMESTAMP_FORMATTER = new SimpleDateFormat(
- "dd-MMM-yyyy HH:mm:ss");
-
- private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(
- "dd-MMM-yyyy");
-
-
-
-
-
-
-
- public CSVWriter(Writer writer) {
- this(writer, DEFAULT_SEPARATOR);
- }
-
-
-
-
-
-
-
-
-
- public CSVWriter(Writer writer, char separator) {
- this(writer, separator, DEFAULT_QUOTE_CHARACTER);
- }
-
-
-
-
-
-
-
-
-
-
-
- public CSVWriter(Writer writer, char separator, char quotechar) {
- this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public CSVWriter(Writer writer, char separator, char quotechar,
- char escapechar) {
- this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public CSVWriter(Writer writer, char separator, char quotechar,
- String lineEnd) {
- this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public CSVWriter(Writer writer, char separator, char quotechar,
- char escapechar, String lineEnd) {
- this.rawWriter = writer;
- this.pw = new PrintWriter(writer);
- this.separator = separator;
- this.quotechar = quotechar;
- this.escapechar = escapechar;
- this.lineEnd = lineEnd;
- }
-
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public void writeAll(List allLines) {
-
- for (Iterator iter = allLines.iterator(); iter.hasNext();) {
- String[] nextLine = (String[]) iter.next();
- writeNext(nextLine);
- }
-
- }
-
- protected void writeColumnNames(ResultSetMetaData metadata)
- throws SQLException {
-
- int columnCount = metadata.getColumnCount();
-
- String[] nextLine = new String[columnCount];
- for (int i = 0; i < columnCount; i++) {
- nextLine[i] = metadata.getColumnName(i + 1);
- }
- writeNext(nextLine);
- }
-
-
-
-
-
-
-
-
-
-
-
-
- public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames)
- throws SQLException, IOException {
-
- ResultSetMetaData metadata = rs.getMetaData();
-
- if (includeColumnNames) {
- writeColumnNames(metadata);
- }
-
- int columnCount = metadata.getColumnCount();
-
- while (rs.next()) {
- String[] nextLine = new String[columnCount];
-
- for (int i = 0; i < columnCount; i++) {
- nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1),
- i + 1);
- }
-
- writeNext(nextLine);
- }
- }
-
- private static String getColumnValue(ResultSet rs, int colType, int colIndex)
- throws SQLException, IOException {
-
- String value = "";
-
- switch (colType) {
- case Types.BIT:
- Object bit = rs.getObject(colIndex);
- if (bit != null) {
- value = String.valueOf(bit);
- }
- break;
- case Types.BOOLEAN:
- boolean b = rs.getBoolean(colIndex);
- if (!rs.wasNull()) {
- value = Boolean.valueOf(b).toString();
- }
- break;
- case Types.CLOB:
- Clob c = rs.getClob(colIndex);
- if (c != null) {
- value = read(c);
- }
- break;
- case Types.BIGINT:
- case Types.DECIMAL:
- case Types.DOUBLE:
- case Types.FLOAT:
- case Types.REAL:
- case Types.NUMERIC:
- BigDecimal bd = rs.getBigDecimal(colIndex);
- if (bd != null) {
- value = "" + bd.doubleValue();
- }
- break;
- case Types.INTEGER:
- case Types.TINYINT:
- case Types.SMALLINT:
- int intValue = rs.getInt(colIndex);
- if (!rs.wasNull()) {
- value = "" + intValue;
- }
- break;
- case Types.JAVA_OBJECT:
- Object obj = rs.getObject(colIndex);
- if (obj != null) {
- value = String.valueOf(obj);
- }
- break;
- case Types.DATE:
- java.sql.Date date = rs.getDate(colIndex);
- if (date != null) {
- value = DATE_FORMATTER.format(date);
- ;
- }
- break;
- case Types.TIME:
- Time t = rs.getTime(colIndex);
- if (t != null) {
- value = t.toString();
- }
- break;
- case Types.TIMESTAMP:
- Timestamp tstamp = rs.getTimestamp(colIndex);
- if (tstamp != null) {
- value = TIMESTAMP_FORMATTER.format(tstamp);
- }
- break;
- case Types.LONGVARCHAR:
- case Types.VARCHAR:
- case Types.CHAR:
- value = rs.getString(colIndex);
- break;
- default:
- value = "";
- }
-
- if (value == null) {
- value = "";
- }
-
- return value;
-
- }
-
- private static String read(Clob c) throws SQLException, IOException {
- StringBuffer sb = new StringBuffer((int) c.length());
- Reader r = c.getCharacterStream();
- char[] cbuf = new char[2048];
- int n = 0;
- while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
- if (n > 0) {
- sb.append(cbuf, 0, n);
- }
- }
- return sb.toString();
- }
-
-
-
-
-
-
-
-
- public void writeNext(String[] nextLine) {
-
- if (nextLine == null)
- return;
-
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < nextLine.length; i++) {
-
- if (i != 0) {
- sb.append(separator);
- }
-
- String nextElement = nextLine[i];
- if (nextElement == null)
- continue;
- if (quotechar != NO_QUOTE_CHARACTER)
- sb.append(quotechar);
- for (int j = 0; j < nextElement.length(); j++) {
- char nextChar = nextElement.charAt(j);
- if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
- sb.append(escapechar).append(nextChar);
- } else if (escapechar != NO_ESCAPE_CHARACTER
- && nextChar == escapechar) {
- sb.append(escapechar).append(nextChar);
- } else {
- sb.append(nextChar);
- }
- }
- if (quotechar != NO_QUOTE_CHARACTER)
- sb.append(quotechar);
- }
-
- sb.append(lineEnd);
- pw.write(sb.toString());
-
- }
-
-
-
-
-
-
-
- public void flush() throws IOException {
-
- pw.flush();
-
- }
-
-
-
-
-
-
-
-
- public void close() throws IOException {
- pw.flush();
- pw.close();
- rawWriter.close();
- }
-
- }
生成文件测试类
- public class CSVWriterTest {
-
-
-
-
-
-
-
-
-
-
- private String invokeWriter(String[] args) throws IOException {
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw, ',', '\'');
- csvw.writeNext(args);
- return sw.toString();
- }
-
-
-
-
-
-
-
-
- public void testParseLine() throws IOException {
-
-
- String[] normal = { "a", "b", "c" };
- String output = invokeWriter(normal);
- assertEquals("'a','b','c'\n", output);
-
-
- String[] quoted = { "a", "b,b,b", "c" };
- output = invokeWriter(quoted);
- assertEquals("'a','b,b,b','c'\n", output);
-
-
- String[] empty = {,};
- output = invokeWriter(empty);
- assertEquals("\n", output);
-
-
- String[] multiline = { "This is a \n multiline entry", "so is \n this" };
- output = invokeWriter(multiline);
- assertEquals("'This is a \n multiline entry','so is \n this'\n", output);
-
- }
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
-
- public void testParseAll() throws IOException {
-
- List allElements = new ArrayList();
- String[] line1 = "Name#Phone#Email".split("#");
- String[] line2 = "Glen#1234#glen@abcd.com".split("#");
- String[] line3 = "John#5678#john@efgh.com".split("#");
- allElements.add(line1);
- allElements.add(line2);
- allElements.add(line3);
-
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(new FileWriter("d:/test.csv"), ',', '\'');
- csvw.writeAll(allElements);
-
-
-
-
-
-
- }
-
-
-
-
-
-
-
- public void testNoQuoteChars() throws IOException {
-
- String[] line = { "Foo", "Bar", "Baz" };
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR,
- CSVWriter.NO_QUOTE_CHARACTER);
- csvw.writeNext(line);
- String result = sw.toString();
-
- assertEquals("Foo,Bar,Baz\n", result);
- }
-
-
-
-
-
-
-
-
- public void testNullValues() throws IOException {
-
- String[] line = { "Foo", null, "Bar", "baz" };
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw);
- csvw.writeNext(line);
- String result = sw.toString();
-
- assertEquals("\"Foo\",,\"Bar\",\"baz\"\n", result);
-
- }
-
-
- public void testStreamFlushing() throws IOException {
-
- String WRITE_FILE = "d:/myfile.csv";
-
- String[] nextLine = new String[] { "aaaa", "bbbb", "cccc", "dddd" };
-
- FileWriter fileWriter = new FileWriter(WRITE_FILE);
- CSVWriter writer = new CSVWriter(fileWriter);
-
- writer.writeNext(nextLine);
-
-
- writer.close();
-
- }
-
- public void testAlternateEscapeChar() {
- String[] line = { "Foo", "bar's" };
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR,
- CSVWriter.DEFAULT_QUOTE_CHARACTER, '\'');
- csvw.writeNext(line);
- assertEquals("\"Foo\",\"bar''s\"\n", sw.toString());
- }
-
- public void testNoQuotingNoEscaping() {
- String[] line = { "\"Foo\",\"Bar\"" };
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR,
- CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
- csvw.writeNext(line);
- assertEquals("\"Foo\",\"Bar\"\n", sw.toString());
- }
- @Test
-
- public void testNestedQuotes() {
- String[] data = new String[] { "\"\"", "test" };
- String oracle = new String("\"\"\"\"\"\",\"test\"\n");
-
- CSVWriter writer = null;
- File tempFile = null;
- FileWriter fwriter = null;
-
- try {
- tempFile = File.createTempFile("csvWriterTest", ".csv");
- tempFile.deleteOnExit();
- fwriter = new FileWriter(tempFile);
- writer = new CSVWriter(fwriter);
- } catch (IOException e) {
- fail();
- }
-
-
- writer.writeNext(data);
-
- try {
- writer.close();
- } catch (IOException e) {
- fail();
- }
-
- try {
-
- fwriter.flush();
- fail();
- } catch (IOException e) {
-
- }
-
-
- FileReader in = null;
- try {
- in = new FileReader(tempFile);
- } catch (FileNotFoundException e) {
- fail();
- }
-
- StringBuffer fileContents = new StringBuffer();
- try {
- int ch;
- while ((ch = in.read()) != -1) {
- fileContents.append((char) ch);
- }
- in.close();
- } catch (IOException e) {
- fail();
- }
-
- assertTrue(oracle.equals(fileContents.toString()));
- }
-
- public void testAlternateLineFeeds() {
- String[] line = { "Foo", "Bar", "baz" };
- StringWriter sw = new StringWriter();
- CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR,
- CSVWriter.DEFAULT_QUOTE_CHARACTER, "\r");
- csvw.writeNext(line);
- String result = sw.toString();
-
- assertTrue(result.endsWith("\r"));
-
- }
-
-
-
-
-
-
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(CSVWriterTest.class);
- }
-
- }
其二:EXCEL文件的读取与生成(要用到jxl.jar, 上网可以搜到,我下面附上)
- public class ExcelHandle {
- public ExcelHandle() {
- }
-
-
-
-
-
-
- public static void readExcel(String filePath) {
- try {
- InputStream is = new FileInputStream(filePath);
- Workbook rwb = Workbook.getWorkbook(is);
-
- Sheet st = rwb.getSheet("original");
- Cell c00 = st.getCell(0, 0);
-
- String strc00 = c00.getContents();
-
- if (c00.getType() == CellType.LABEL) {
- LabelCell labelc00 = (LabelCell) c00;
- strc00 = labelc00.getString();
- }
-
- System.out.println(strc00);
-
- rwb.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- public static void writeExcel(OutputStream os) {
- try {
-
-
-
-
-
-
-
- WritableWorkbook wwb = Workbook.createWorkbook(os);
-
- WritableSheet ws = wwb.createSheet("Test Sheet 1", 0);
-
-
-
-
- Label label = new Label(0, 0, "this is a label test");
- ws.addCell(label);
-
-
- WritableFont wf = new WritableFont(WritableFont.TIMES, 18,
- WritableFont.BOLD, true);
- WritableCellFormat wcf = new WritableCellFormat(wf);
- Label labelcf = new Label(1, 0, "this is a label test", wcf);
- ws.addCell(labelcf);
-
-
- WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10,
- WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
- jxl.format.Colour.RED);
- WritableCellFormat wcfFC = new WritableCellFormat(wfc);
- Label labelCF = new Label(1, 0, "This is a Label Cell", wcfFC);
- ws.addCell(labelCF);
-
-
- Number labelN = new Number(0, 1, 3.1415926);
- ws.addCell(labelN);
-
-
- NumberFormat nf = new NumberFormat("#.##");
- WritableCellFormat wcfN = new WritableCellFormat(nf);
- Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
- ws.addCell(labelNF);
-
-
- Boolean labelB = new jxl.write.Boolean(0, 2, false);
- ws.addCell(labelB);
-
-
- jxl.write.DateTime labelDT = new jxl.write.DateTime(0, 3,
- new java.util.Date());
- ws.addCell(labelDT);
-
-
- DateFormat df = new DateFormat("dd MM yyyy hh:mm:ss");
- WritableCellFormat wcfDF = new WritableCellFormat(df);
- DateTime labelDTF = new DateTime(1, 3, new java.util.Date(), wcfDF);
- ws.addCell(labelDTF);
-
-
- File image = new File("E:\\2.png");
- WritableImage wimage = new WritableImage(0, 1, 2, 2, image);
- ws.addImage(wimage);
-
- wwb.write();
- wwb.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
-
-
- public static void modifyExcel(File file1, File file2) {
- try {
- Workbook rwb = Workbook.getWorkbook(file1);
- WritableWorkbook wwb = Workbook.createWorkbook(file2, rwb);
- WritableSheet ws = wwb.getSheet(0);
- WritableCell wc = ws.getWritableCell(0, 0);
-
- if (wc.getType() == CellType.LABEL) {
- Label label = (Label) wc;
- label.setString("The value has been modified");
- }
- wwb.write();
- wwb.close();
- rwb.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public static void main(String[] args) {
- try {
-
-
-
- File fileWrite = new File("E:/testWrite.xls");
- fileWrite.createNewFile();
- OutputStream os = new FileOutputStream(fileWrite);
- ExcelHandle.writeExcel(os);
-
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
其三:读取CSV文件内容写入到Excel中(此代码含有同步数据库的操作)
- public static void readCsv(String fileDir, Set targetSet) {
- System.out.println("执行解析文件............");
- try {
- CSVReader csvr = new CSVReader(new FileReader(fileDir), ',', '\"',
- 1);
- List allElements = csvr.readAll();
- int size = allElements == null ? 0 : allElements.size();
- System.out.println("总共有几行:" + size);
- csvr = new CSVReader(new FileReader(fileDir), ',', '\"', 1);
- String[] nextline = null;
-
- File tempFile = new File("d:/output2.xls");
- WritableWorkbook workbook;
- workbook = Workbook.createWorkbook(tempFile);
- WritableSheet sheet = workbook.createSheet("kk", 1);
- Label l = null;
- WritableFont detFont = new WritableFont(WritableFont.ARIAL, 10,
- WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
- jxl.format.Colour.BLACK);
- WritableCellFormat detFormat = new WritableCellFormat(detFont);
-
- int column = 0;
- l = new Label(column++, 0, "KPI_CODE", detFormat);
- sheet.addCell(l);
-
- l = new Label(column++, 0, "KPI_DESC", detFormat);
- sheet.addCell(l);
-
- l = new Label(column++, 0, "KPI_VALUE", detFormat);
- sheet.addCell(l);
-
- l = new Label(column++, 0, "KPI_MAX", detFormat);
- sheet.addCell(l);
-
- l = new Label(column++, 0, "KPI_MIN", detFormat);
- sheet.addCell(l);
-
- l = new Label(column++, 0, "MONTH_ID", detFormat);
- sheet.addCell(l);
-
- for (int i = 0; i < size; i++) {
- TargetRecordPojo tp = new TargetRecordPojo();
- nextline = csvr.readNext();
- int len = nextline.length;
-
- for (int j = 0; j < len; j++) {
-
- l = new Label(j, i + 1, nextline[j], detFormat);
- sheet.addCell(l);
-
- if (j == 0) {
- tp.setTarget_id(nextline[0]);
-
- continue;
- } else if (j == 1) {
- tp.setRemark(nextline[1]);
-
- continue;
-
- } else if (j == 2) {
- tp.setTarget_value(nextline[2]);
-
- continue;
-
- } else if (j == 3) {
- tp.setTarget_data_max(nextline[3]);
-
- continue;
-
- } else if (j == 4) {
- tp.setTarget_data_min(nextline[4]);
-
- continue;
-
- } else if (j == 5) {
-
- tp.setTarget_date(nextline[5]);
-
-
- continue;
- }
-
- }
-
- targetSet.add(tp);
-
- }
- column = 0;
- sheet.setColumnView(column++, 20);
- sheet.setColumnView(column++, 20);
- sheet.setColumnView(column++, 20);
- sheet.setColumnView(column++, 20);
- sheet.setColumnView(column++, 20);
- sheet.setColumnView(column++, 20);
- workbook.write();
- workbook.close();
- FileInputStream fis = new FileInputStream(tempFile);
- FileOutputStream fos = new FileOutputStream(new File(
- "d:/backupfile/backup_" + System.currentTimeMillis()
- + ".xls"));
- byte[] buff = new byte[1024];
- int len = -1;
- while ((len = fis.read(buff)) != -1) {
- fos.write(buff, 0, len);
-
- }
- fis.close();
- fos.flush();
- fos.close();
- tempFile.delete();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- } catch (RowsExceededException e) {
-
- e.printStackTrace();
- } catch (WriteException e) {
-
- e.printStackTrace();
- }
-
- }
分享到:
相关推荐
以上就是使用C#读取Excel和CSV文件,将数据加载到Chart控件并绘制折线图的基本过程。根据实际需求,你可能需要对数据进行预处理,例如过滤、排序或计算。此外,还可以通过调整Chart的样式和设置来优化视觉效果,如...
在处理数据分析和可视化的场景中,pandas库和matplotlib库是Python编程语言中最为常用的两个库,它们各自有着丰富的...希望本文对pandas模块读取csv文件和excel表格以及使用matplotlib画图的介绍能够对大家有所帮助。
下面我们将深入探讨如何在Java中正确地读取和写入CSV文件,以及解决中文乱码的问题。 1. **字符编码的理解**: - 在处理中文字符时,必须确保使用正确的字符编码,例如UTF-8。UTF-8是一种广泛支持的编码格式,可以...
在IT行业中,处理数据时,Excel和CSV文件是非常常见的格式,尤其在数据分析、报表生成以及数据交换等场景中。本话题主要围绕“NPOI读写Excel”和“第三方DLL读写CSV文件”这两个核心知识点展开,同时提供了一系列...
在Excel中,VBA可以编写宏,这些宏是预定义的指令序列,可以执行一系列操作,如打开文件、编辑数据或生成报告。在“VBA批量处理csv或其他excel文件数据”的场景下,我们可以通过编写VBA宏实现以下功能: 1. **遍历...
C#读取CSV EXCEL文件的知识点解析 C#读取CSV EXCEL文件是指使用C#语言读取CSV(Comma Separated Values,逗号分隔值)文件和EXCEL文件的方法。CSV文件是一种通用的文本文件格式,用于存储表格数据,而EXCEL文件是一...
在Excel VBA编程中,有时我们需要处理大量的数据,这时候可以借助外部数据访问对象(ADO)来读取和操作数据,比如CSV(逗号分隔值)文件。CSV格式因其通用性和简洁性,常用于数据交换。下面我们将详细介绍如何使用...
假设上述csv文件保存为”A.csv”,如何用Python像操作Excel一样提取其中的一行,也就是一条记录,利用Python自带的csv模块,有2种方法可以实现: 方法一:reader 第一种方法使用reader函数,接收一个可迭代的对象...
CSV文件,全称为“逗号分隔值”(Comma ...总的来说,CSV文件的生成与分析是数据处理中的基础技能,无论是在日常办公还是在开发环境中都有着广泛的应用。了解并掌握这些技能,能够帮助我们更有效地管理和利用数据。
在本实验中,我们将探讨如何在STM32F103ZE上实现FATFS文件系统,以及如何生成并写入CSV文件。 FATFS是DOS/Windows兼容的FAT文件系统的轻量级实现,适用于资源有限的嵌入式系统。它提供了一个通用的文件操作接口,...
在IT行业中,尤其是在数据分析、报表生成以及数据迁移等任务中,C#编程语言与CSV(逗号分隔值)文件和Excel的交互是常见的应用场景。本篇将详细讲解如何使用C#来读取CSV文件并将数据导入到Excel中。 首先,我们需要...
codesys通过文件写入...d、通过SysFileClose关闭CSV文件,若文件不关闭,则下次无法读取和写入。 本文所采用的codesys版本为V3.5.14.10,参考博客地址:https://blog.csdn.net/qq_19979629/article/details/124355867
总结来说,这个主题涉及到的关键技术包括Qt的文本I/O操作,自定义的CSV解析策略,以及使用第三方库SimpleXlsxWriter生成Excel文件。这些技能对于构建能处理复杂数据任务的桌面应用程序至关重要。在实际项目中,...
6. 测试环境准备:描述中提到“测试需要手动修改TP数据库配置”,意味着在测试环境中,可能需要创建一个新的数据库或修改现有数据库的连接参数,以便与CSV文件数据的导入导出操作匹配。 7. 压缩包文件内容: - `....
文档文件
创建的CSV文件可被Excel、Python、R等工具读取,方便进行进一步的数据分析和处理。 8. **学习资源**: - 官方文档:LabVIEW的帮助文档提供了详细的编程指南和例子。 - 在线社区:如NI的LAVA论坛,你可以找到许多...
某汽车整车生产企业需要将其车辆发车信息发布到汽车产业链平台上去,其数据为内部ERP系统生成的Excel数据表,用户首先将该数据表上传至汽车产业链平台,平台将此Excel数据读取导入到平台内部的SQL Sever数据库中,以...
本文将深入探讨Qt中的QTableWidget与CSV文件之间的关系,以及如何在两者之间进行数据交互。 首先,理解QTableWidget的基本操作至关重要。QTableWidget可以创建带有行和列的表格,每个单元格都可以存储不同类型的...
在标题“XlS批量生成CSV 多个CSV合并为1个CSV”中,涉及到的主要知识点是Excel文件(XLS)的批处理转换以及多个CSV文件的合并。这些操作在数据分析、报表整理、数据库导入等场景中非常实用。 首先,我们需要理解XLS...
6. **错误处理**:在处理CSV文件时,需要考虑可能的异常,如文件不存在、读写权限问题等。使用`Try...Catch`结构可以捕获并处理这些异常。 7. **性能优化**:如果文件非常大,一次性加载到内存可能会消耗大量资源。...