Popular Posts
android.intent.action.SCREEN_ON & android.intent.action.SCREEN_OFF First, I've tried create a receiver to receive screen on/off and register receiver on AndroidManifest.xml like below, but unfortunately ... Memo: Debounce Task To prevent multi-execution from caller in short time, use debounce for single execution. var debounce = function (func, threshold, execAsap... Multiple line of text limit With Sharepoint Designer, edit the page of list view. Add xsl template as below to override original template. Source template could be foun...
Blog Archive
Stats
Spinner Sample
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SpinnerSample extends JFrame {

    public SpinnerSample() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(new Dimension(500, 500));
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(new Point((d.width - this.getWidth()) / 2, (d.height - this.getHeight()) / 2));

        GridBagLayout layout = new GridBagLayout();
        GridBagConstraints cons = new GridBagConstraints();
        this.setLayout(layout);

        cons.insets = new Insets(5, 5, 5, 5);
        cons.gridx = 0;
        cons.gridy = 0;
        cons.anchor = GridBagConstraints.WEST;
        cons.fill = GridBagConstraints.HORIZONTAL;

        JSpinner spinner = null;

        spinner = new JSpinner(new SpinnerDateModel());
        //spinner.setEditor(new JSpinner.DateEditor(spinner, "yyyy/MM/dd HH:mm"));
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        cons.gridy++;
        spinner = new JSpinner(new SpinnerListModel(new String[] { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" }));
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        cons.gridy++;
        spinner = new JSpinner(new SpinnerNumberModel());
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        this.setVisible(true);
        this.pack();
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new SpinnerSample();
    }
}
Formatter review
// %[argument_index$][flags][width][.precision]conversion

// (b/B) boolean
System.out.printf("result : %1$b %2$b %3$b %n", false, new Boolean(true), null);
// result : false true false

// (h/H) Integer.toHexString(arg.hashCode())
System.out.printf("result : %1$h %2$h %n", "bruce", 12);
// result : 59a9547 c

// (s/S) arg.toString()
System.out.printf("result : %1$s %2$s %n", 10, "bruce");
// result : 10 bruce

// (c/C) character
System.out.printf("result : %1$c %2$c %n", 'c', '\u0051');
// result : c Q

// (d, o, x/X) integral
System.out.printf("result : %1$d %1$o %1$x %n", 1024);
// result : 1024 2000 400
System.out.printf("result : %1$d %1$o %1$x %n", 1024);
// result : 1024 (   1024) 0001024 

// (e/E, f, g/G, a/A) floating point
System.out.printf("result : %1$e %1$f %1$g %1$a %n", 1234.567);
// result : 1.234567e+03 1234.567000 1234.57 0x1.34a449ba5e354p10
System.out.printf("result : %1$f (%1$7.2f) %1$07.0f %1$07.2f%n", 1234.567);
// result : 1234.567000 (1234.57) 0001235 1234.57

// date/time (R, T, r, D, F, c)
System.out.printf("result : %tR %n", Calendar.getInstance());
// result : 09:53
System.out.printf("result : %tT %n", Calendar.getInstance());
// result : 09:53:18
System.out.printf("result : %tr %n", Calendar.getInstance());
// result : 09:53:18 上午
System.out.printf("result : %tD %n", Calendar.getInstance());
// result : 06/10/10
System.out.printf("result : %tF %n", Calendar.getInstance());
// result : 2010-06-10
System.out.printf("result : %tc %n", Calendar.getInstance());
// result : 星期四 六月 10 09:53:18 CST 2010
System.out.printf("result : %1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS", Calendar.getInstance());
// result : 2010/06/10 11:02:38
other date args http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#dt
LogonUser Function : impersonate a windows user
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES: 
// This sample can be run only on Windows XP.  The default Windows 2000 security policy 
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk. 
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked, 
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
    const int LOGON32_LOGON_INTERACTIVE = 2;
    const int LOGON32_LOGON_NETWORK = 3;
    const int LOGON32_LOGON_BATCH = 4;
    const int LOGON32_LOGON_SERVICE = 5;
    const int LOGON32_LOGON_UNLOCK = 7;
    const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_PROVIDER_WINNT50 = 3;
    const int LOGON32_PROVIDER_WINNT40 = 2;
    const int LOGON32_PROVIDER_WINNT35 = 1;

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    //[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    //private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
    //    int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

    // Test harness.
    // If you incorporate this code into a DLL, be sure to demand FullTrust.
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static void Main2(string[] args)
    {
        IntPtr tokenHandle = new IntPtr(0);
        IntPtr dupeTokenHandle = new IntPtr(0);
        try
        {
            string userName, domainName;
            // Get the user token for the specified user, domain, and password using the 
            // unmanaged LogonUser method.  
            // The local machine name can be used for the domain name to impersonate a user on this machine.
            Console.Write("Enter the name of the domain on which to log on: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);

            tokenHandle = IntPtr.Zero;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }

            Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
            Console.WriteLine("Value of Windows NT token: " + tokenHandle);

            // Check the identity.
            Console.WriteLine("Before impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            // Check the identity.
            Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);

            // Stop impersonating the user.
            impersonatedUser.Undo();

            // Check the identity.
            Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);

            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }

        Console.Read();
    }

}
or
public class ImpersonateIdentity : IDisposable
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static ImpersonateIdentity Impersonate(string userName, string password, string domainName)
    {
        ImpersonateIdentity identity = new ImpersonateIdentity();

        const int LOGON32_PROVIDER_DEFAULT = 0;
        //This parameter causes LogonUser to create a primary token.
        const int LOGON32_LOGON_INTERACTIVE = 2;

        // Call LogonUser to obtain a handle to an access token.
        bool returnValue = LogonUser(userName, domainName, password,
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out identity.safeTokenHandle);

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }

        identity.impersonatedUser = WindowsIdentity.Impersonate(identity.safeTokenHandle.DangerousGetHandle());
        return identity;
    }

    WindowsImpersonationContext impersonatedUser;
    SafeTokenHandle safeTokenHandle;

    private ImpersonateIdentity() { }

    public void Dispose()
    {
        if (impersonatedUser != null) impersonatedUser.Dispose();
        if (safeTokenHandle != null) safeTokenHandle.Dispose();
    }
}

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}
reference : or
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
namespace ConsoleApplication1
{
    class Class1
    {
        //登入
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken
        );
            
        //登出
        [DllImport("kernel32.dll")]
        public extern static bool CloseHandle(IntPtr hToken);

        public Class1()
        {
            string UserName = "username";
            string MachineName = "192.168.0.10";
            string Pw = "password";
            string IPath = @"\\" + MachineName + @"\shared";
            
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
            
            IntPtr tokenHandle = new IntPtr(0);
            tokenHandle = IntPtr.Zero;
            
            //將登入的Token放在tokenHandle
            bool returnValue = LogonUser(
                UserName,
                MachineName,
                Pw,
                LOGON32_LOGON_NEW_CREDENTIALS,
                LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle
            );

            //讓程式模擬登入的使用者
            WindowsIdentity w = new WindowsIdentity(tokenHandle);
            w.Impersonate();
            if (false == returnValue)
            {
                //登入失敗的處理
                return;
            }
            //取得該目錄下的所有檔案名稱
            DirectoryInfo dir = new DirectoryInfo(IPath);
            FileInfo[] inf = dir.GetFiles();
            for (int i = 0; i < inf.Length; i++)
            {
                Console.WriteLine(inf[i].Name);
            }
        }
    }
}
Condition : in a domain
LogonUser(
    UserName,
    "myDomain",
    Pw,LOGON32_LOGON_NEW_CREDENTIALS,
    LOGON32_PROVIDER_DEFAULT,
    ref tokenHandle
);
reference : [C#]在程式中模擬特定的windows帳號存取網路芳鄰
Active Directory authentication
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main(string[] args)
    {
        string domain = "mydomain";
        string account = "bruce";
        string password = "12345678";

        Console.WriteLine(IsAuthenticated1(domain, account, password));
        Console.WriteLine(IsAuthenticated2(domain, account, password));
        Console.WriteLine(IsAuthenticated3(domain, account, password));
        Console.Read();
    }

    static bool IsAuthenticated1(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            object o = entry.NativeObject;
            isAuthenticated = true;
            entry.Close();
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated2(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = string.Format("(sAMAccountName={0})", account);
            SearchResult result = searcher.FindOne();
            entry.Close();
            isAuthenticated = true;
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated3(string domain, string account, string password)
    {
        try
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
            return pc.ValidateCredentials(account, password);
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}
Searialize object as JSON
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person("Bruce", "Tsai");
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, person);
        ms.Close();
        string json = Encoding.Default.GetString(ms.ToArray());
        Console.WriteLine(json);
        Console.Read();
    }
}


[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}
JSONHelper
public class JSONHelper
{

    public static string ToJson(object obj)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        ms.Close();
        string json = Encoding.UTF8.GetString(ms.ToArray());
        return json;
    }

    public static T ParseJson<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
        DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
        obj = (T)ser.ReadObject(ms);
        ms.Close();
        return obj;
    }
}
Query index data
1. Start window service Indexing Service
2. Create a new category and start indexing.
class Program
{
    static void Main(string[] args)
    {
        // reference : http://msdn.microsoft.com/en-us/library/ms690516
        string strCatalog = "TestIndexing";
        string strKeyword = "readme";  // search keyword
        string strQuery = string.Format(
            @"SELECT path, FileName, size, write, attrib FROM SCOPE() WHERE FREETEXT('{0}')",
            //@"SELECT * FROM FILEINFO WHERE FREETEXT('{0}')",
            strKeyword
        );
 
        string connstring = "Provider=MSIDXS.1;Integrated Security .='';Data Source=" + strCatalog;
 
        DataSet set = null;
        try
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, connstring))
            {
                adapter.Fill(set = new DataSet());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return;
        }
 
        foreach (DataRow row in set.Tables[0].Rows)
        {
            Console.WriteLine("{0} |{1} @{2}", row["FileName"], row["size"], row["write"]);
        }
        Console.Read();
    }
}
Create barcode
import java.io.File;
import java.io.FileNotFoundException;

import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import net.sourceforge.barbecue.output.OutputException;

public class Program {

    /**
     * @param args
     * @throws FileNotFoundException
     * @throws BarcodeException
     * @throws OutputException
     */
    public static void main(String[] args) throws FileNotFoundException, BarcodeException, OutputException {
        // TODO Auto-generated method stub

        Barcode code = BarcodeFactory.create3of9("123456789", true);
        BarcodeImageHandler.savePNG(code, new File("barcode.png"));

    }

}
Library : http://barbecue.sourceforge.net/
Simple Web snapshot
import java.util.Date;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class WebSnap {

    public static final int PNG = SWT.IMAGE_PNG;
    public static final int BMP = SWT.IMAGE_BMP;
    public static final int JPG = SWT.IMAGE_JPEG;
    public static final int GIF = SWT.IMAGE_GIF;
    public static final int TIFF = SWT.IMAGE_TIFF;

    private Display display;
    private Shell shell;
    private Browser browser;

    /**
     * 截圖寬度
     */
    private int width;
    /**
     * 截圖高度
     */
    private int height;

    /**
     * @param width
     *            截圖寬度
     * @param height
     *            截圖高度
     * @param url
     *            目標網址URL
     */
    public WebSnap(int width, int height, String url) {
        this.width = width;
        this.height = height;
        this.display = new Display();

        this.shell = new Shell(this.display);
        this.shell.setLayout(new FillLayout());
        this.shell.setSize(width, height);
        this.shell.setText("Web Snap");

        this.browser = new Browser(this.shell, SWT.NONE);
        this.browser.setSize(width, height);
        this.browser.setUrl(url);
    }

    /**
     * @param file
     *            圖片存檔路徑
     * @param swtImageType
     *            圖片存檔類型
     */
    private void snap(String file, int swtImageType) {
        Image data = new Image(this.display, this.width, this.height);
        this.browser.print(new GC(data));
        ImageLoader il = new ImageLoader();
        il.data = new ImageData[] { data.getImageData() };
        il.save(file, swtImageType);
        data.dispose();
    }

    /**
     * @param file
     *            圖片存檔路徑
     * @param swtImageType
     *            圖片存檔類型
     * @param sleepTick
     *            延遲時間
     */
    public void asynSnap(final String file, final int type, final long sleepTick) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(sleepTick);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                WebSnap.this.display.asyncExec(new Runnable() {
                    public void run() {
                        WebSnap.this.snap(file, type);
                        WebSnap.this.shell.dispose();
                    }
                });
            };
        }.start();
        this.waitForDispose();
    }

    private void waitForDispose() {
        while (!this.shell.isDisposed()) {
            if (!this.display.readAndDispatch()) {
                this.display.sleep();
            }
        }
        this.display.dispose();
    }

    public static void main(String[] args) {
        int width = 1024, height = 768;
        String url = "http://tw.yahoo.com";
        String file = String.format("w%d.png", new Date().getTime());

        WebSnap ws = new WebSnap(width, height, url);
        ws.asynSnap(file, WebSnap.PNG, 18000);
    }

}
File operation at SMB / UNC (network neighborhood)
import java.io.IOException;
import java.io.OutputStreamWriter;

import jcifs.Config;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

public class Program {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        StringBuilder sb = new StringBuilder("<html><head><title>9 x 9</title></head><body><table border='1'>");
        sb.append(System.getProperty("line.separator"));
        for (int i = 1; i < 10; i++) {
            sb.append("<tr>");
            for (int j = 1; j < 10; j++) {
                sb.append(String.format("<td>%d x %d = %d</td>", i, j, i * j));
            }
            sb.append("</tr>");
            sb.append(System.getProperty("line.separator"));
        }
        sb.append("</table></body></html>");

        Config.setProperty("jcifs.smb.client.domain", "mydomain");
        Config.setProperty("jcifs.smb.client.username", "bruce");
        Config.setProperty("jcifs.smb.client.password", "12345678");

        SmbFile remotePath = new SmbFile("file://computer_name/mis/subfolder/test.html");
        // SmbFile remotePath = new SmbFile("smb://hostname/upload$/test.html");

        SmbFileOutputStream sfos = new SmbFileOutputStream(remotePath);
        OutputStreamWriter osw = new OutputStreamWriter(sfos);
        osw.write(sb.toString());
        osw.close();
        sfos.close();
    }

}
Library : http://jcifs.samba.org/
Export excel using html format cause leading zero disappeared
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication4
{
    class Program
    {
        static char[] vs = "qazxswedcvfrtgb nhyujmkioplPLOKIJU HYGTFRDESWSQAZXCVBNM ".ToCharArray();
 
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder(@"<html xmlns:o=""urn:schemas-microsoft-com:office:office""
xmlns:x=""urn:schemas-microsoft-com:office:excel""
xmlns=""http://www.w3.org/TR/REC-html40"">
<head>
</head><table border=""1""><thead><tr><th>column A</th><th>column B</th><th>column C</th><th>column D</th></tr></thead><tbody>");
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                    sb.AppendFormat(
                        @"<tr><td>{0}</td><td>{1}</td><td x:str=""{2:0000000000}"">{2:0000000000}</td><td>{3}</td></tr>",
                        getRandomWord(r),
                        r.NextDouble(),
                        r.Next(10000000),
                        "test"
                    ).AppendLine();
            }
            sb.Append("</tbody></body></html>");
 
            System.IO.File.WriteAllText("z:/test.xls", sb.ToString());
        }
 
        static string getRandomWord(Random r)
        {
            int length = r.Next(5, 15);
            StringBuilder sb = new StringBuilder();
            while (length-- > 0)
            {
                sb.Append(vs[r.Next(vs.Length - 1)]);
            }
            return sb.ToString();
        }
    }
}
(export without x:str attribute)
(export with x:str attribute)

Use xml format example

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="Sheet1">
    <Table  ss:DefaultColumnWidth="54" ss:DefaultRowHeight="16.5">
      <Row>
        <Cell>
          <Data ss:Type="String">KPmBYSAYyugQe</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.96726507412608</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0000197334</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">XdpptxEYqEf</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.734600760850404</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0001564744</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">RbkWExnsMfJNHS</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.666254851346023</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0003279746</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">OBbRffRJP</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.721114829052759</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0007181989</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">ZHdLm MohfByWd</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.270307757551925</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0008739388</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">kNqGnHE</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.895800942506548</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0001980657</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">xYr yJdeKp</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.462409074633573</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0002466265</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">GZvyMV</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.921151050795406</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0000487429</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">AysRFgIMuUfwCE</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.102547224193135</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0009025478</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
      <Row>
        <Cell>
          <Data ss:Type="String">RYaFkSvWhWd</Data>
        </Cell>
        <Cell>
          <Data ss:Type="Number">0.313286157936457</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">0007754057</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">test</Data>
        </Cell>
      </Row>
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
      <ProtectObjects>False</ProtectObjects>
      <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
  </Worksheet>
</Workbook>
Reference : http://msdn.microsoft.com/en-us/library/bb226687%28v=office.11%29.aspx
Object serialize/ deserialize
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TransientMember {

    /**
     * @param args
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // create new user with account & password
        User user = new User();
        user.account = "bruce";
        user.password = "mypassword";
        System.out.println(user);
        // serialize
        byte[] buffer = user.serialize();

        // deserialize from byte array
        User user2 = User.deserialize(buffer);
        System.out.println(user2);
    }

}

class User implements Serializable {
    public String account;
    transient public String password;  // would not be serialize

    @Override
    public String toString() {
        return String.format("<user account:%s password:%s>", this.account, this.password);
    }

    public byte[] serialize() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);
        oos.close();
        baos.close();
        return baos.toByteArray();
    }

    public static User deserialize(byte[] buf) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object o = ois.readObject();
        ois.close();
        bais.close();
        return (User) o;
    }
}