C # How to Write Data to excel? (Code tutorial ),
C # How to Write Data to excel? (Code tutorial)
Using NPOI. HSSF. UserModel; using NPOI. XSSF. UserModel; public static void write1 () {// method for creating the 2003 file version. Create a workbook. HSSFWorkbook workbook2003 = new HSSFWorkbook (); // create a new Sheet worksheet workbook2003.CreateSheet ("Sheet1"); // obtain the worksheet named Sheet1 HSSFSheet SheetOne = (HSSFSheet) workbook2003.GetSheet ("Sheet1"); // Add rows to the worksheet. The subscript starts from 0 for (int I = 0; I <10; I ++) {SheetOne. createRow (I); // create 10 rows} // create 10 cells for each row. HSSFRow SheetRow = (HSSFRow) SheetOne. getRow (0); // obtain the first HSSFCell [] SheetCell = new HSSFCell [10]; for (int I = 0; I <10; I ++) {// create the SheetCell [I] = (HSSFCell) SheetRow for each row in sequence. createCell (I);} // after creation, the value of SheetCell [0] can be assigned. setCellValue (true); // The value is bool SheetCell [1]. setCellValue (0.000001); // assign a value to the floating point SheetCell [2]. setCellValue ("Excel2003"); // assign a value to the string SheetCell [3]. setCellValue ("123456789987654321"); // assign a value to a long string for (int I = 4; I <10; I ++) {// cyclically assign an integer SheetCell [I]. setCellValue (I);} FileStream file = new FileStream (@ "D: \ Excel1.xls ", FileMode. Create); workbook2003.Write (file); file. Close (); workbook2003.Close (); // method for creating the 2007 file version. Create a workbook. XSSFWorkbook workbook2007 = new XSSFWorkbook (); // create a new Sheet worksheet workbook2007.CreateSheet ("Sheet1"); // obtain the worksheet XSSFSheet SheetOne2007 = (XSSFSheet) workbook2007.GetSheet ("Sheet1"); // Add rows to the worksheet. The subscript starts from 0 for (int I = 0; I <10; I ++) {SheetOne2007.CreateRow (I ); // create 10 rows} // create 10 cells for each row. XSSFRow SheetRow2007 = (XSSFRow) SheetOne2007.GetRow (0 ); // obtain the first XSSFCell [] SheetCell2007 = new XSSFCell [10]; for (int I = 0; I <10; I ++) of the Sheet1 worksheet) {// create the SheetCell2007 [I] = (XSSFCell) SheetRow2007.CreateCell (I) ;}// assign a value to SheetCell2007 [0] after each row is created. setCellValue (true); // The value is bool SheetCell2007 [1]. setCellValue (0.000001); // The value is a floating point SheetCell2007 [2]. setCellValue ("Excel2003"); // assign a value to the string SheetCell2007 [3]. setCellValue ("123456789987654321"); // assign a value to a long string for (int I = 4; I <10; I ++) {// cyclically assign a value to the integer SheetCell2007 [I]. setCellValue (I);} FileStream file2007 = new FileStream (@ "D: \ Excel1.xlsx", FileMode. create); workbook2007.Write (file2007); file. close (); workbook2007.Close ();}