Since both the i5-6400 and i7-8700k share the same socket type: FCLGA1151. It means they are physically compatible, so it should be possible to upgrade from one to the other. You might need to reset and update your BIOS firmware. However, the bigger concern is that the i7-8700k is a 130W part while your existing i5-6400 is a 65W part. That is an additional 65W of power and heat that you need to account for. \
You might need to upgrade the Power Supply as these pre-made systems typically come with a minimally sized PSU. You can check this by measuring the power consumption of your system at load from the wall outlet. Then look at the rating on the PSU to determine how much margin you have. You will also need to account for the additional heat. You can upgrade the fan/heatsink connected to your CPU for starters and if your case only has 1 or 2 fans, you can install another one. Temperature can be checked in the UEFI/BIOS settings. You should keep upgrading your cooling until your load temperature is below 75 degrees Celsius.