天天看點

2011/12/2

今天終于把dbf的到處完全的弄好了,也不出亂碼了。

将資料庫的表導出為dbf格式檔案的方法。

dao層代碼:

通過Hibernate的Session繞過hibernate直接使用SQL語言擷取列的資訊和所有的資料供為javaDbf類提供資料生成dbf檔案。

public Map findInfoAndData() throws SQLException {
		// TODO Auto-generated method stub
		Session session = getHibernateTemplate().getSessionFactory()
				.openSession();
		Transaction ts = session.beginTransaction();
		Connection conn = session.connection();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from detail");

		ResultSetMetaData meta = rs.getMetaData();   
		// 去掉最後一列importId
		int columnCount = meta.getColumnCount();   //表字段的個數
		String[] strutName = new String[columnCount];  //字段名字
		byte[] strutType = new byte[columnCount];  // 字段類型
		int[] strutLength = new int[columnCount];  //字段長度
		rs.last();
		int itemCount = rs.getRow();  //記錄總數
		System.out.println("***" + columnCount + "***" + itemCount);
		int i = 0;
		rs.beforeFirst();
		Object[][] data = new Object[itemCount][columnCount];
		int k;
		for (k = 0; k < columnCount; k++) {   //擷取表中字段的資訊
			strutName[i] = meta.getColumnName(k + 1);
			strutType[i] = (byte) meta.getColumnType(k + 1);
			strutLength[i] = meta.getColumnDisplaySize(k + 1);
			if (strutLength[i] > 100) {
				strutLength[i] = 100;
			}
			System.out.println("----導入測試----:" + i + ":" + "strutName:"
					+ strutName[i] + "||strutType:" + strutType[i]
					+ "||strutLength:" + strutLength[i]);
			i++;
		}

		i = 0;
		int j;
		// rs.first();
		rs.beforeFirst();
		// while(!meta.getColumnName(temp).trim().equals("zpxx")){
		for (int rr = 0; rr < itemCount && rs.next(); rr++) {
			j = 0;
			for (k = 0; k < columnCount; k++) {   //擷取所有資料
				data[i][j] = rs.getObject(k + 1);
				// System.out.print("第"+i+"行第"+j+"列:"+","+data[i][j]);
				j++;
			}
			i++;
			// System.out.println();
			// System.out.println();
		}
		ts.commit();
		session.close();
		HashMap map = new HashMap();  //用哈希表儲存所有的資料
		map.put("strutName", strutName);
		map.put("strutType", strutType);
		map.put("strutLength", strutLength);
		map.put("data", data);

		return map;
	}
           

struts.xml中的配置資訊

<action name="exportDetailDbf" class="dbfOperateAction" method="exportDetailDbf">
			<result name="success" type="downloadResult"></result>//自定義result類用于輸出檔案
		</action>
           

Action類中的代碼

擷取map中的資訊,對資訊進行處理,然後生成dbf檔案。

public String exportDetailDbf() {
		title = "detail.dbf";
		if (dbfStream != null)
			dbfStream = null;
		Map map = detailService.findInfoAndData();
		String[] strutName = (String[]) map.get("strutName");
		byte[] strutType = (byte[]) map.get("strutType");
		int[] strutLength = (int[]) map.get("strutLength");
		Object[][] data = (Object[][]) map.get("data");
		int columnCount = strutName.length;
		int rowCount = detailService.findDetailSize();

		try {
			ExportDBF.typeMapping(strutType, columnCount, data, rowCount);  //資料處理
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		dbfStream = ExportDBF.generateDbfFromArray(strutName, strutType,  //dbf生成
				strutLength, data);
		return SUCCESS;

	}
           

ExportDBF類中的代碼:

public static String dbfPath = "d:/";
	public static boolean state = true;

	
	/**
	 * JavaDBF中的字段類型表示和ResultSetMetaData中的字段類型表示應該是不一緻的, 這裡做一個類型映射和轉換即可
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public static synchronized void typeMapping(byte[] strutType,
			int fieldCount, Object[][] data, int rowCount)
			throws UnsupportedEncodingException {
		// System.out.println("rowcount:" + rowCount);
		for (int i = 0; i < fieldCount; i++) {  //将所有的資料進行轉換
			int count = 0;
			switch (strutType[i]) {
			case 1: // char
				strutType[i] = DBFField.FIELD_TYPE_C;
				// System.out.println("測試:1:" + strutType[i] + "||第" + i);
				for (int j = 0; j < rowCount; j++) {
					if (data[j][i] == null || data[j][i].equals("")) {
						data[j][i] = "";
					} else {
						data[j][i] = (new String(
								(data[j][i].toString()).getBytes("GBK")))
								.trim();  //以GBK的編碼方式提取位元組數組然後重新構
					}                                 //造字元串
				}
				// System.out.println("測試:1:");
			case 2: // 如果為numeric
				strutType[i] = DBFField.FIELD_TYPE_N;
				// System.out.println("測試:2:" + strutType[i]);
				for (int j = 0; j < rowCount; j++) {
					// System.out.println("----測試:----2:" + data[j][i] + ">" + j
					// + ">" + i + "||");
					if (data[j][i] == null || data[j][i].equals("")) {
						data[j][i] = "";
					} else {
						// System.out.println("測試:2--0:");
						data[j][i] = (new String(
								(data[j][i].toString()).getBytes("GBK")))
								.trim();

						// System.out.println("測試:2--1:");
					}
				}
				// System.out.println("測試:2:");
			case 4: // integer
			case 6: // folat
			case 8: // double
			case 12:// varchar
				strutType[i] = DBFField.FIELD_TYPE_C;
				// System.out.println("測試:3:" + strutType[i]);
				for (int j = 0; j < rowCount; j++) {
					// System.out.println("----測試:----3:" + data[j][i]);
					if (data[j][i] == null || data[j][i].equals("")) {
						data[j][i] = "";
					} else {
						data[j][i] = new String(
								(data[j][i].toString()).getBytes("GBK")).trim();
						System.out.print(data[j][i].toString().length());
					}
				}
				// System.out.println("測試:4:");
			case 16: // boolean
			case 93:
				strutType[i] = DBFField.FIELD_TYPE_C;
				// System.out.println("測試:3:" + strutType[i]);
				for (int j = 0; j < rowCount; j++) {
					// System.out.println("----測試:----3:" + data[j][i]);
					if (data[j][i] == null || data[j][i].equals("")) {
						data[j][i] = "";
					} else {
						data[j][i] = new String(
								(data[j][i].toString()).getBytes("GBK")).trim();
						System.out.print(data[j][i].toString().length());
					}
				}
			default:
				strutType[i] = DBFField.FIELD_TYPE_C;
				// System.out.println("測試:3:" + strutType[i]);
				for (int j = 0; j < rowCount; j++) {
					// System.out.println("----測試:----3:" + data[j][i]);
					if (data[j][i] == null || data[j][i].equals("")) {
						data[j][i] = "";
					} else {
						data[j][i] = new String(
								(data[j][i].toString()).getBytes("GBK")).trim();
						System.out.print(data[j][i].toString().length());
					}
				}
				break;
			}

		}
	}

	// 寫入dbf檔案
	public static synchronized ByteArrayOutputStream generateDbfFromArray(
			String[] strutName, byte[] strutType, int[] strutLength,
			Object[][] data) {

		ByteArrayOutputStream ba = new ByteArrayOutputStream();

		try

		{
			int fieldCount = strutName.length;
			// fieldCount = 27;
			int rowCount = data.length;
			System.out.println("***" + fieldCount + "***" + rowCount);
			DBFField[] fields = new DBFField[fieldCount];

			int i = 0;
			for (int k = 0; k < fieldCount; k++) {
				fields[i] = new DBFField();
				String s;
				if (strutName[i].length() > 10) {
					s = (String) strutName[i].substring(0, 9);
				} else
					s = strutName[i];
				fields[i].setName(s);
				fields[i].setDataType(strutType[i]);
				// fields[i].setFieldLength(strutLength[i] + 1);//by liukun
				// +1中文問題
				// fields[i].setFieldLength(strutLength[i] );
				// 以下是最新解決辦法,如果是奇數,+1,偶數,不加
				System.out.println("&&&&&&&&" + strutLength[i]);
				if (strutLength[i] < 0)
					strutLength[i] = 6;  //設定最小的長度為6防止資料顯示不完全
				if (strutLength[i] < 4)
					strutLength[i] = 6;
				if (strutLength[i] % 2 == 0)
					fields[i].setFieldLength(strutLength[i]);
				else
					fields[i].setFieldLength(strutLength[i] + 1);
				System.out.println(strutName[i] + "," + strutType[i] + ","
						+ fields[i].getFieldLength());

				i++;
			}
			DBFWriter writer = new DBFWriter();
			writer.setCharactersetName("GBK");  //設定編碼字元集為GBK

			writer.setFields(fields);

			for (i = 0; i < rowCount; i++) {

				writer.addRecord(data[i]);
			}

			writer.write(ba);
			return ba;

		}

		catch (Exception e)

		{
			state = false;
			e.printStackTrace();
			return null;
		}

	}
           

 項目進展:添加了将将資料庫資料生成dbf檔案,和另外的一些小功能。

上一篇: 2011/12/5
下一篇: 2011/12/1