Export all data in DataGridView to local excel
When the method is called, the parameter can be written into its own DataGridView name
#region DataGridView Export to local Excel file method
public void DownloadDataGridView(DataGridView dgv)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Execl files (*.xls)|*.xls",
FilterIndex = 0,
RestoreDirectory = true,
CreatePrompt = true,
Title = "Exported Excel"
};
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
{
return;
}//end if
Stream myStream = saveFileDialog.OpenFile();
//use the default encode
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dgv.ColumnCount; i++)
{
str += dgv.Columns[i].HeaderText;
str += "\t";
}//end for
sw.WriteLine(str);
for (int j = 0; j < dgv.Rows.Count - 1; j++)
{
string strTemp = "";
for (int k = 0; k < dgv.Columns.Count; k++)
{
object obj = dgv.Rows[j].Cells[k].Value;
if (obj != null)
{
strTemp += dgv.Rows[j].Cells[k].Value.ToString();
}//end if
else
{
strTemp = "";
}//end else
strTemp += "\t";
}//end for k
sw.WriteLine(strTemp);
}//end for j
sw.Close();
myStream.Close();
MessageBox.Show("Success to Export the Excel File:\n" + saveFileDialog.FileName);
}//end try
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//end catch
finally
{
sw.Close();
myStream.Close();
}//end finally
}
#endregion
Read More:
- Grep: How to Find All the Files Containing a String in Linux
- hive: How to Process Data (Delete, View, Query, and etc)
- [Ubuntu] How to Solve dpkg Error: dpkg: error: failed to open package info file ‘/usr/local/var/lib/dpkg/status’ for reading: No such file or directory
- [Solved] Xshelln Connect to Local VM linux Error: Could not connect to ‘XXX.168.122.1‘ (port 22): Connection failed
- Git error when switching branches: Your local changes to the following files would be overwritten by checkout
- Solution to gzip: stdin: invalid compressed data — format violated error in decompressing. Tgz file under Linux
- How to fix the ERROR: Failed to build gem native extension in Centos 8
- How to Use Annotations in Flutter & Dart
- Git pull error: Your local changes to the following files would be overwritten by me
- C#: How to Use Itextsharp to Manipulate PDF Files
- How to Solve labelme Install Error in Ubuntu
- How to Create Threads in Linux
- [Solved] Error (suppressible): (vsim-12110) All optimizations are disabled because the -novopt option is in effect…
- How to Solve Error: Address already in use
- How to Delete New Memory in Vector
- [Solved] Node uploads files to FTP server error: timed out while making data connection
- How to Fix No default.conf file in conf.d after Installing Nginx
- How to Solve Xmind Install Error in Ubuntu System
- Vue uses localstorage and sessionstorage to store data
- How to Solve Mujoco Install Error in Ubuntu (Pycharm Run Error)