Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - In C#, I want to export the data of the last two columns from an access database file (.mdb), similar to figure 1, to a. txt file.
In C#, I want to export the data of the last two columns from an access database file (.mdb), similar to figure 1, to a. txt file.
Because the table has several columns, it is not convenient to use txt, but excel.

Please refer to the code I learned before. Npoi runs excel. Download Npoi.dll first, and then add a reference to it in the project.

The following dt is a DataTable object. You first get data from the database and fill it in dt. Then continue with the following code.

IWorkbook? Workbook? =? New? hssf workbook(); ? //Create a workbook in memory. In excel, an excel file is a workbook.

ISheet? Sheets? =? Workbook. CreateSheet ("release sheet"); //Create a table in the workbook, namely sheet 1 and sheet2. After opening excel. .

//Next, create rows and cells for the spreadsheet and assign values.

For what? (int? Me? =? 0; ? Me? & lt? dt。 Number of rows. Count; ? I++)//dt creates as many rows as the worksheet.

{

IRow? r? =? Sheets. create row(I); //i indicates which line to create.

For what? (int? j? =? 0; ? j? & lt? dt。 Number of columns; ? J++)//dt Create as many cells as there are columns in the worksheet.

{

ICell? c? =? R. creating a unit (j); //Create the j-th cell for row r.

c.SetCellValue(dt。 Line [i][j] ToString()); //Set the display content of cell C, which is the first line of dt and the first J grid.

}

}

Use? (FileStream? fs? =? Documents. Create(@ "c:\ \ 2. xls ")// Creates a file stream object fs, which is linked to the specified path.

{

Workbook. Write (fs); //Write the workbook to the file stream fs.

}