//Create the data set and tableDataSet ds = new DataSet("New_DataSet");DataTable dt = new DataTable("New_DataTable");
//Set the locale for eachds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)OleDbConnection con = new OleDbConnection(dbConnectionString);con.Open();
//Create a query and fill the data table with the data from the DBstring sql = "SELECT Whatever FROM MyDBTable;";OleDbCommand cmd = new OleDbCommand(sql, con);OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;adptr.Fill(dt);con.Close();
//Add the table to the data setds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data setExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME)){helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;helper.CurrentSheetName = "Sheet1";helper.CurrentPosition = new CellRef("C3");
//the template xlsx should contains the named range "header"; use the command "insert"/"name".helper.InsertRange("header");
//the template xlsx should contains the named range "sample1";//inside this range you should have cells with these values://<name> , <value> and <comment>, which will be replaced by the values from the getSample()CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});helper.InsertRange(sample1, getSample());
//you could use here other named ranges to insert new cells and call InsertRange as many times you want,//it will be copied one after another;//even you can change direction or the current cell/sheet before you insert
//typically you put all your "template ranges" (the names) on the same sheet and then you just delete ithelper.DeleteSheet("Sheet3");}
其中示例如下所示:
private IEnumerable<List<object>> getSample(){var random = new Random();
for (int loop = 0; loop < 3000; loop++){yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};}}
public class GridViewExportUtil{public static void Export(string fileName, GridView gv){HttpContext.Current.Response.Clear();HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter()){using (HtmlTextWriter htw = new HtmlTextWriter(sw)){// Create a form to contain the gridTable table = new Table();
// add the header row to the tableif (gv.HeaderRow != null){GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);table.Rows.Add(gv.HeaderRow);}
// add each of the data rows to the tableforeach (GridViewRow row in gv.Rows){GridViewExportUtil.PrepareControlForExport(row);table.Rows.Add(row);}
// add the footer row to the tableif (gv.FooterRow != null){GridViewExportUtil.PrepareControlForExport(gv.FooterRow);table.Rows.Add(gv.FooterRow);}
// render the table into the htmlwritertable.RenderControl(htw);
// render the htmlwriter into the responseHttpContext.Current.Response.Write(sw.ToString());HttpContext.Current.Response.End();}}}
/// <summary>/// Replace any of the contained controls with literals/// </summary>/// <param name="control"></param>private static void PrepareControlForExport(Control control){for (int i = 0; i < control.Controls.Count; i++){Control current = control.Controls[i];if (current is LinkButton){control.Controls.Remove(current);control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));}else if (current is ImageButton){control.Controls.Remove(current);control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));}else if (current is HyperLink){control.Controls.Remove(current);control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));}else if (current is DropDownList){control.Controls.Remove(current);control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));}else if (current is CheckBox){control.Controls.Remove(current);control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));}
if (current.HasControls()){GridViewExportUtil.PrepareControlForExport(current);}}}}
//Creates a new instance for ExcelEngine.ExcelEngine excelEngine = new ExcelEngine();//Loads or open an existing workbook through Open method of IWorkbooksIWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);//To-Do some manipulation|//To-Do some manipulation//Set the version of the workbook.workbook.Version = ExcelVersion.Excel2013;//Save the workbook in file system as xlsx formatworkbook.SaveAs(outputFileName);
IList<DummyPerson> dummyPeople = new List<DummyPerson>();//Add data to dummyPeople...IExportEngine engine = new ExcelExportEngine();engine.AddData(dummyPeople);MemoryStream memory = engine.Export();
{Name = "myExcelFile.xslx",File = new Microsoft.Graph.File()};
// Create an empty file in the user's OneDrive.var excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);
// Add the contents of a template Excel file.DriveItem excelDriveItem;using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource)){//Upload content to the file. ExcelTestResource is an empty template Excel file.//https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontentexcelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);}
using (var ew = new ExcelWriter("C:\\temp\\test.xlsx")){for (var row = 1; row <= 10; row++){for (var col = 1; col <= 5; col++){ew.Write($"row:{row}-col:{col}", col, row);}}}
Imports DocumentFormat.OpenXmlImports DocumentFormat.OpenXml.PackagingImports DocumentFormat.OpenXml.Spreadsheet
Public Class ExportExcelClassPublic Sub New()
End Sub
Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)' Create a spreadsheet document by supplying the filepath.' By default, AutoSave = true, Editable = true, and Type = xlsx.Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)
' Add a WorkbookPart to the document.Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPartworkbook.Workbook = New Workbook
' Add a WorksheetPart to the WorkbookPart.Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()Worksheet.Worksheet = New Worksheet(New SheetData())
' Add Sheets to the Workbook.Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())
Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()Dim Header As Row = New Row()Header.RowIndex = CType(1, UInt32)
For Each column As DataColumn In table.ColumnsDim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)Header.AppendChild(headerCell)Next
data.AppendChild(Header)
Dim contentRow As DataRowFor i As Integer = 0 To table.Rows.Count - 1contentRow = table.Rows(i)data.AppendChild(createContentRow(contentRow, i + 2))Next
End Sub
Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As CellDim cell As Cell = New Cell()cell.DataType = CellValues.InlineString
cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString
Dim inlineString As InlineString = New InlineString()Dim t As Text = New Text()t.Text = cellValue.ToString()inlineString.AppendChild(t)cell.AppendChild(inlineString)Return cellEnd Function
Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As RowDim row As Row = New Row With {.rowIndex = CType(rowIndex, UInt32)}
For i As Integer = 0 To dataRow.Table.Columns.Count - 1Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))row.AppendChild(dataCell)Next
Return rowEnd Function
Private Function getColumnName(ByVal columnIndex As Integer) As StringDim dividend As Integer = columnIndexDim columnName As String = String.EmptyDim modifier As Integer
While dividend > 0modifier = (dividend - 1) Mod 26columnName = Convert.ToChar(65 + modifier).ToString() & columnNamedividend = CInt(((dividend - modifier) / 26))End While
Return columnNameEnd FunctionEnd Class
string sUrlFile = "G:\\ReportAmortizedDetail.xls";Workbook workbook = new Workbook();workbook.LoadFromFile(sUrlFile);//Get the 1st sheetWorksheet sheet = workbook.Worksheets[0];//Specify the cell rangeCellRange range = sheet.Range["A15"];//Find all matched text in the rangeCellRange[] cells = range.FindAllString("hi", false, false);//Replace textforeach (CellRange cell in range){cell.Text = "";}//Saveworkbook.Save();
var workbook = new Aspose.Cells.Workbook(sUrlFile);// access first (default) worksheetvar sheet = workbook.Worksheets[0];// access CellsCollection of first worksheetvar cells = sheet.Cells;// write HelloWorld to cells A1cells["A15"].Value = "";// save spreadsheet to discworkbook.Save(sUrlFile);workbook.Dispose();workbook = null;
public class CreateFileOrFolder{static void Main(){//// https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder//// https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file//// .NET Framework 4.7.2//// Specify a name for your top-level folder.string folderName = @"C:\Users\david\Desktop\Book3";
// To create a string that specifies the path to a subfolder under your// top-level folder, add a name for the subfolder to folderName.
string pathString = System.IO.Path.Combine(folderName, "_rels");System.IO.Directory.CreateDirectory(pathString);pathString = System.IO.Path.Combine(folderName, "docProps");System.IO.Directory.CreateDirectory(pathString);pathString = System.IO.Path.Combine(folderName, "xl");System.IO.Directory.CreateDirectory(pathString);
string subPathString = System.IO.Path.Combine(pathString, "_rels");System.IO.Directory.CreateDirectory(subPathString);subPathString = System.IO.Path.Combine(pathString, "theme");System.IO.Directory.CreateDirectory(subPathString);subPathString = System.IO.Path.Combine(pathString, "worksheets");System.IO.Directory.CreateDirectory(subPathString);// Keep the console window open in debug mode.System.Console.WriteLine("Press any key to exit.");System.Console.ReadKey();}}